【问题标题】:check if value is in an array list javascript检查值是否在数组列表javascript中
【发布时间】:2023-03-11 04:10:02
【问题描述】:

我想检查 my_array_list 中是否存在 'a' = 1 和 'b' = 2 的数组,如果存在,则返回索引。

my_array_list = [{ 'a' : 5, 'b' : 2, 'c' : 3}, { 'a' : 1, 'b' : 2, 'c' : 3}, { 'a' : 5, 'b' : 4, 'c' : 3}]

不起作用的代码结构:

var a = 1
var b = 2

if (a in my_array_list and b in my_array_list){
    print (index)
}

【问题讨论】:

  • 请检查并批准答案

标签: javascript node.js arrays


【解决方案1】:

使用array.find

my_array_list = [{ 'a' : 5, 'b' : 2, 'c' : 3}, { 'a' : 1, 'b' : 2, 'c' : 3}, { 'a' : 5, 'b' : 4, 'c' : 3}];

const node = my_array_list.find(node => node.a === 1 && node.b ===2);

const index = my_array_list.indexOf(node);

console.log(node, index);

如果您对查找节点不感兴趣,可以直接使用array.findIndex

my_array_list = [{ 'a' : 5, 'b' : 2, 'c' : 3}, { 'a' : 1, 'b' : 2, 'c' : 3}, { 'a' : 5, 'b' : 4, 'c' : 3}];

const index = my_array_list.findIndex(node => node.a === 1 && node.b ===2);

console.log(index);

【讨论】:

  • findIndex 我认为是最好的选择,因为它会在一行中给出结果,而不是首先找到值然后去索引
  • 如果用户不打算找到节点,那么他可以选择这个。
【解决方案2】:

解决办法

现在你的数组 b=2 是两倍,所以它选择第一个 b=2 的索引

var my_array_list = [{ 'a' : 5, 'b' : 2, 'c' : 3}, { 'a' : 1, 'b' : 2, 'c' : 3}, { 'a' : 5, 'b' : 4, 'c' : 3}]

  
  
    
var index = my_array_list.findIndex(x => x.a ===1);
var index2 = my_array_list.findIndex(x => x.b ===2);


console.log("index of a=1",index);
console.log("index of b=2",index2);

【讨论】:

  • 应该是my_array_list.findIndex(x => x.a === 1 && x.b ===2);
  • 是的,可以,但如果有人想单独找到,那么这个解决方案适合他们
【解决方案3】:

const my_array_list = [
  { 'a' : 5, 'b' : 2, 'c' : 3},
  { 'a' : 1, 'b' : 2, 'c' : 3},
  { 'a' : 5, 'b' : 4, 'c' : 3}
]

const findIndex = (arr, valA, valB) => {
  for (const i in arr) {
    const { a, b } = arr[i]
    if (a === valA && b === valB) return Number(i)
  }

  // Didn't find
  return -1
}

const index = findIndex(my_array_list, 1, 2)
console.log(index)

【讨论】:

    【解决方案4】:

    my_array_list = [{ 'a' : 5, 'b' : 2, 'c' : 3}, { 'a' : 1, 'b' : 2, 'c' : 3}, { 'a' : 5, 'b' : 4, 'c' : 3}];
    var a = 1
    var b = 2
    var obj = my_array_list.find(x => x.a === a && x.b ===b);
    var index = my_array_list.indexOf(obj );
    console.log(index);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-19
      • 1970-01-01
      • 2012-06-30
      • 2020-09-15
      • 2011-12-06
      • 1970-01-01
      相关资源
      最近更新 更多