例如,我想检查数组是否包含值数组而不是值
var arr = [1, 2, 3];
arr.contains([1, 2]); // returns true
// and
arr.contains([1, 5]); // must be false
有一个名为 contains in underscore
_.contains
的方法,但它的工作方式类似于 javascript 中的 .indexof()
而不是它返回 true 和false 并且只查找值而不查找数组
还有一个方法Array.prototype.includes()在 javascript 中也接受单个输入而不是数组
最佳答案
actually I want to check if second array has all the keys present in first array I want to check with
AND
for example
[1,2,3,4].contains([1,4])
must return true where as[1,2,3,4].contains([1,9])
must return false, hope this makes sense, I'm for now using underscores intersection and second array with intersection result it must be same, its still long procedure....
您可以在 for
循环中使用 Array.prototype.includes()
var arr = [1,2,3,4];
function contains(arr) {
for (var i = 0, included = true; i < arr.length
; included = included && this.includes(arr[i]), i++);
return included
}
Array.prototype.contains = contains;
console.log(arr.contains([1, 4]), arr.contains([9, 1]), arr.contains([1, 5]))
关于javascript - 有没有优雅的函数可以在数组中查找数组? JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35861093/