我需要2d数组,所以我做了嵌套数组,因为JavaScript不允许它们.
它们看起来像那样:
var myArray = [ [1, 0], [1, 1], [1, 3], [2, 4] ]
如何[0,1]
在vanilla JS中检查此数组是否包含特定元素(即其中一个数组)?
这是我尝试过的,没有成功(一切都返回false
)(编辑:我在答案中包含了答案):
var myArray = [
[1, 0],
[1, 1],
[1, 3],
[2, 4]
]
var itemTrue = [2, 4];
var itemFalse = [4, 4];
function contains(a, obj) {
var i = a.length;
while (i--) {
if (a[i] === obj) {
return true;
}
}
return false;
}
// EDIT : first answer's solution
function isArrayInArray(x, check) {
for (var i = 0, len = x.length; i < len; i++) {
if (x[i][0] === check[0] && x[i][1] === check[1]) {
return true;
}
}
return false;
}
// EDIT : accepted answer's solution
function isArrayInArray2(x, check) {
var result = x.find(function(ele) {
return (JSON.stringify(ele) === JSON.stringify(check));
})
return result !=null
}
console.log("true :" + myArray.includes(itemTrue));
console.log("false :" + myArray.includes(itemFalse));
console.log("true :" + (myArray.indexOf(itemTrue) != -1));
console.log("false :" + (myArray.indexOf(itemFalse) != -1));
console.log("true :" + contains(myArray, itemTrue));
console.log("false :" + contains(myArray, itemFalse));
// EDIT : first answer's solution
console.log("true :" + isArrayInArray(myArray, itemTrue));
console.log("false :" + isArrayInArray(myArray, itemFalse));
// EDIT : accepted answer's solution
console.log("true :" + isArrayInArray2(myArray, itemTrue));
console.log("false :" + isArrayInArray2(myArray, itemFalse));
它可能看起来像重复但我找不到类似的问题.如果是,请随意标记.
简短而简单,将数组字符串化并作为字符串进行比较
function isArrayInArray(arr, item){ var item_as_string = JSON.stringify(item); var contains = arr.some(function(ele){ return JSON.stringify(ele) === item_as_string; }); return contains; } var myArray = [ [1, 0], [1, 1], [1, 3], [2, 4] ] var item = [1, 0] console.log(isArrayInArray(myArray, item)); // Print true if found
在这里查看一些文档