【问题标题】:how to get an index of an array if the checked value is in the nested array?如果检查的值在嵌套数组中,如何获取数组的索引?
【发布时间】:2020-07-01 06:51:46
【问题描述】:

我有一个这样的数组

const myArray = [ [ false ], [ true ], [ false ] ] 

我想从上面的数组中获取 value == true 的元素的索引。

所以因为上面数组中的true在第二个元素中,所以我想得到1作为索引结果

怎么做?

【问题讨论】:

标签: javascript


【解决方案1】:

你只需要为此添加过滤器,

const myArray = [ [ false ], [ true ], [ false ] ] 

let result = myArray.filter(function(value) {
    return value[0]=== true;
});

【讨论】:

  • 返回一个过滤后的数组,而不是数组的索引为真值。
【解决方案2】:
const arrays = [ [ false ], [ true ], [ false ] ] 

const index = [].concat.apply([], arrays).findIndex(value => value === true)

【讨论】:

    【解决方案3】:

    你可以用 map 方法循环你的数组

    
    const arr = [ [ false ], [ true ], [ false ] ] 
    
    arr.map((item, index) => {
    
    if (item[0]) {
      console.log(index)
    }
    
    })
    
    

    【讨论】:

    • map 返回一个新数组。如果以后不使用,那就没有意义了。
    【解决方案4】:
    const idx = myArray.findIndex(i => i[0]);
    

    【讨论】:

    • 仅使用代码发布答案不好,请始终解释您的答案。
    • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。
    • 代码非常简单,我认为它不言自明,注意到其他答案要么不提供解释,要么提供相当多余的单行。 IMO这仍然是最好的答案。接受的答案是完全错误的,而另一个被赞成的答案使用了一种难以阅读的数组展平技术,确实需要解释。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-07
    • 2021-12-31
    • 1970-01-01
    • 2021-08-11
    相关资源
    最近更新 更多