假设我有一个具有以下值的数组 -
var arr = [true, true, false, false, false, true, false];
我正在寻找可以给我以下输出的逻辑 -
[0,1,5]
您可以.reduce()
一次性完成此操作:
const arr = [true, true, false, false, false, true, false]
const indices = arr.reduce(
(out, bool, index) => bool ? out.concat(index) : out,
[]
)
console.log(indices)
你开始通过传递一个空数组[]
作为initialValue
到.reduce()
并使用三元?
运营商以确定是否.concat()
对index
与否。
或者,您可以使用更新的.flatMap()
方法:
const arr = [true, true, false, false, false, true, false]
const indices = arr.flatMap((bool, index) => bool ? index : [])
console.log(indices)
如果您的浏览器尚不支持它,您将获得一个Uncaught TypeError: arr.flatMap is not a function
. 在这种情况下,您可以从这里使用我的 polyfill 定义。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句