javascript - 过滤器不返回索引值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);
解决方案
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);
推荐阅读
- javascript - 使用 javascript 从文本中获取 DOM 正文
- ios - 尝试使用后台任务在 10 秒后检索粘贴板值
- r - R闪亮的r-markdown:同步放大图表
- r - 无法在不覆盖的情况下将 R 数据框插入现有 Excel 文件
- python - 在 Matplotlib 中创建 pdp 图的子图
- ffmpeg - FFmpeg 在文本文件中传递参数
- python - 抛出显示差异的异常
- c++ - 在多线程中创建 QSqlDatabase 连接时如何防止名称冲突
- .net-core - 将 3rd 方库重新打包为 NuGet 包
- html - 我的 25% 宽度的 flex 项目在包装后占用 100% 的宽度