使用 reduce 查找项目在数组中的次数。 该数组可以递归地包含数组。
var foo = [
1,
[2, 3, 4],
4, [5,6,7], 4
];
bar(foo, 4)
会返回 3。
最佳答案
使用 Array.prototype.reduce
试试这个.
var foo = [1, [2, 3, 4], 4, [5, 6, 7], 4];
function f(arr, item) {
return arr.reduce(function (s, i) {
if (Array.isArray(i)) return s+f(i, item);
return s+(i==item?1:0);
}, 0);
}
console.log(f(foo, 4))
函数f
是一个递归函数。我们遍历所有项目并将它们减少为一个数字。该函数也会在所有内部数组上调用,对于非数组项,我们只需检查它们是否等于所需的项。
关于javascript - 使用 reduce 来缩短数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34535645/