StartsWith() 不适用于 takeWhile()

StartsWith() not working with takeWhile()

我正在尝试遍历一个不可变列表并让它 return 一个包含以特定字符串开头的任何条目的新列表。对于此处的示例,我只是试图找到所有以字母 'D' 开头的状态 我希望下面的代码 return 一个大小为 1 和 'Delaware' 的列表作为条目,但它返回一个空列表。

const states = Immutable.fromJS([
    "Alabama",
    "Alaska",
    "Arizona",
    "Arkansas",
    "California",
    "Colorado",
    "Connecticut",
    "Delaware"]);
    
function filter() {
  const testA = 'A';
  const filteredOptions = states.takeWhile((option) =>  option.startsWith(testA));
  console.error(filteredOptions.size); // is 4 as I would expect
  
  const testD = 'D';
  const filteredOptions2 = states.takeWhile((option) =>  option.startsWith(testD));
  console.error(filteredOptions2.size); // is 0 when I expect 1
};

filter();
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

计算机的思维:

Does Alamaba start with A? Yes; I'll take it and continue. Does Alaska start with A? Yes; I'll take it and continue. Does Arizona start with A? Yes; I'll take it and continue. Does Arkansas start with A? Yes; I'll take it and continue. Does California start with A? No, so I stop.

Does Alabama start with D? No, so I stop.

你想要 filter,而不是 takeWhilefilter 将取所有满足命题的元素; takeWhile 仅限序列开头的那些。

有时您只需要 post 就能发现您的错误。我一点击 post 就意识到 takeWhile 一遇到 false 就退出。 A 正在工作,因为它们是列表的开头。

你可以用 filter 来做这个

const statesWhichStartWithLetterD = states.filter(state => state.startsWith('D'));
console.log(statesWhichStartWithLetterD.toJS()); // ["Delaware"]