I know I'm missing something obvious, but I can't seem to find my mistake. I want to see if an array is within another two dimensional array. Here's my code:
var cell = [0, 0];
var populat开发者_如何转开发ion = [[0, 0], [1, 1]];
if (cell == population[0]) {
alert("Cell found within population");
}
else if ([0, 0] == population[0]) {
alert("Array found within population");
}
else {
alert("Neither found within population");
}
I used the second conditional just to be sure that the value of cell and population[0] weren't equivalent. But as it turns out, neither of them match. I've tested (cell[0] == population[0][0]), and that seems to work.
I would appreciate any clarification. Thanks!
The issue here is that the == operator for arrays in javascript compares memory addresses rather than the actual values. This is why you notice that (cell[0] == population[0][0]) returns true (you're comparing values).
You should iterate through the elements in the arrays to compare them. Here's an example of what I mean.
function checkEquivalence(arr1, arr2){
if(arr1.length != arr2.length)
return false;
for (i = 0; i < arr2.length; i++)
{
if(arr1[i] != arr2[i])
return false;
}
return true;
}
Now you can run the operation checkEquivalence( cell, population[0] );
Unfortunately you can't compare arrays directly, you must compare them element-by-element like this:
function compareArrays(arrayOne, arrayTwo) {
if (arrayOne.length != arrayTwo.length) {
return false;
}
for (var i = 0; i < arrayOne.length; ++i) {
if (arrayOne[i] != arrayTwo[i]) {
return false;
}
}
return true;
}
Now you can use:
compareArrays([0, 0], population[0])
...which will yield true.
You probably need some sort of deep equality comparison to see if two objects (including arrays) are "equal" by value. Take a look at Object comparison in JavaScript, or google for Javascript deep equality.
If your comparisons are always going to be this simple, a hackish work around would be:
if(cell.valueOf() == population[0].valueOf()) {
...
}
The above would effective compare two strings, changing the logic to:
if('0,0' == '0,0') {
...
}
Definitely not recommend best-practices by anyone I work with, but is useful in extremely controlled situations.
精彩评论