首页 > 解决方案 > 过滤器不返回索引值javascript

问题描述

我在 js 中有一个字符串,我想记录每个字母实例的索引X

我首先尝试使用map,但这只是undefined与我可以使用的索引一起返回,但需要一个额外的功能。

然后我filter改用了,但不幸的是这没有返回索引。请参见下面的示例:

const str = 'Hello there XXXX, how are you?';

let indexes = str.split('').filter((letter, index) => {
  if(letter === 'X'){
    return index;
  }
});

console.log(indexes);

标签: javascriptecmascript-6

解决方案


forEach我认为使用循环填充索引数组会更好:

  const str = 'Hello there XXXX, how are you?';

  let indexes = [];
  str.split('').forEach((letter, index) => {
    if(letter === 'X'){
      indexes.push(index);
    }
  });

  console.log(indexes);

推荐阅读