0

我正在用 JS 编写代码,我必须测试代码 - 我必须检查 2 个数组中的元素是否相同。所以我有一个数组:boreholes = [[66000, 457000],[1111,2222]....];我想检查这个数组是否包含例如元素。[66000,457000] 所以我做了: boreholes.indexOf([66000,457000])但它返回-1,所以我通过以下方式迭代槽数组:

for (var i = 0; i< boreholes.length; i++){
 if (boreholes[i] == [66000, 457000]){
  console.log('ok');
  break;
 }
};

但我仍然一无所有。有人可以解释一下我做错了什么吗?

4

5 回答 5

3

You cannot compare arrays like array1 == array2 in javascript like you're trying to do here.

Here is a kludge method to compare two arrays:

function isEqual(array1, array2){
  return (array1.join('-') == array2.join('-'));
}

You can now use this method in your code like:

for (var i = 0; i< boreholes.length; i++){
 if (isEqual(boreholes[i], [66000, 457000]){
  console.log('ok');
  break;
 }
};
于 2012-09-06T09:55:28.770 回答
3

您正在比较不同的对象。比较对象时,比较仅评估true被比较的 2 个对象是同一对象的情况。IE

var a = [1,2,3];
var b = a;
a === b //true
b = [1,2,3];
a === b //false, b is not the same object

要像这样比较数组,您需要分别比较它们的所有元素:

for (var i = 0; i < boreholes.length; i++) {
    if (boreholes[i][0] == 66000 && boreholes[i][1] == 457000) {
        console.log('ok');
        break;
    }
}
于 2012-09-06T09:52:01.993 回答
2

目前我有同样的问题,用 toString() 方法

var array1 = [1,2,3,[1,2,3]]
var array2 = [1,2,3,[1,2,3]]

array1 == array2 // false
array1.toString() == array2.toString() // true

var array3 = [1,2,3,[1,3,2]]

// Take attention
array1.toString() == array3.toString() // false
于 2015-06-26T13:58:58.953 回答
0

您也可以使用Underscore.js进行函数式编程的框架。

function containsElements(elements) {
  _.find(boreholes, function(ele){ return _.isEqual(ele, elements); });
}

if(containsElements([66000, 457000])) {
  console.log('ok');
}
于 2012-09-06T10:01:48.177 回答
0

如果数组中可以有两个以上的元素,这个问题还不是很清楚,所以这可能有效

var boreholes = [[66000, 457000],[1111,2222]]; 
var it = [66000, 457000];

function hasIt(boreholes, check) {
  var len = boreholes.length;
  for (var a = 0; a < len; a++) {
    if (boreholes[a][0] == check[0] && boreholes[a][1] == check[1]) {
       // ok
       return true;
    }
  }
  return false;
}

if (hasIt(boreholes, it)) {
  // ok, it has it
}
于 2012-09-06T10:16:05.613 回答