我试图从 Array.filter
方法中返回满足特定条件的项目的索引,但我仍然不断获取实际值数组而不是 我想要的值的索引。
示例:
var seq = [3, 4, 1, 2, 1];
seq.filter((curr, index) => {
if (seq[index + 1] < seq[index]) {
return index;
}
});
// returns [4, 2]
// want to return [1, 3] (the indexes of 4 & 2)
我可以使用更有效的方法吗?我试图避免使用 for 循环。谢谢。
最佳答案
您可以在此处使用reduce
var seq = [3, 4, 1, 2, 1];
var result = seq.reduce((ar, curr, index) => {
if (seq[index + 1] < seq[index]) ar.push(index);
return ar;
}, []);
console.log(result)
关于javascript - 从 Array.filter 内部返回条件 if,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37598404/