首页 > 解决方案 > 如何检查该数组是否包含(数字)数组?

问题描述

我将几个坐标对存储在一个数组中。例如:

[[1,2],[4,5],[7,8]]

我想找到我得到的坐标对。我得到了坐标:

[4,5]

如果数组包含这个坐标,我会得到真否则假。这是我的代码:

function isContain(coords) {
   for (let i = 0; i < array.length; i++) {
       if (array[i].length !== coords.length) return false;

       for (let j = 0; j < array[i].length; j++) {
           if(array[i][j] === coords[j]) {
               return true
           }
       } 
  }
  return false
}

标签: javascriptarrayscoordinates

解决方案


你可以做这样的事情

const foo = [[1, 2], [4, 5], [7, 8]];
const coords = [4, 5];

function isContain(coords) {
  for (const f of foo) {
    if (f[0] === coords[0] && f[1] === coords[1]) {
      return true;
    }
  }
  return false;
}

console.log(isContain(coords));

推荐阅读