bal*_*adb -2 javascript arrays
假设我有一个包含以下值的数组-
var arr = [true, true, false, false, false, true, false];
Run Code Online (Sandbox Code Playgroud)
我正在寻找可以提供以下输出的逻辑-
[0,1,5]
Run Code Online (Sandbox Code Playgroud)
您可以使用.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)Run Code Online (Sandbox Code Playgroud)
你开始通过传递一个空数组[]作为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)Run Code Online (Sandbox Code Playgroud)
如果您的浏览器尚不支持,则会显示Uncaught TypeError: arr.flatMap is not a function。在这种情况下,您可以从此处使用我的polyfill定义。
| 归档时间: |
|
| 查看次数: |
1865 次 |
| 最近记录: |