在 JavaScript/CoffeeScript 中确定一个数组是否包含另一个数组的内容 [英] Determining whether one array contains the contents of another array in JavaScript/CoffeeScript
本文介绍了在 JavaScript/CoffeeScript 中确定一个数组是否包含另一个数组的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 JavaScript 中,如何测试一个数组是否具有另一个数组的元素?
In JavaScript, how do I test that one array has the elements of another array?
arr1 = [1, 2, 3, 4, 5]
[8, 1, 10, 2, 3, 4, 5, 9].function_name(arr1) # => true
推荐答案
没有 set 函数可以做到这一点,但你可以简单地做一个特别的数组交集并检查长度.
No set function does this, but you can simply do an ad-hoc array intersection and check the length.
[8, 1, 10, 2, 3, 4, 5, 9].filter(function (elem) {
return arr1.indexOf(elem) > -1;
}).length == arr1.length
一种更有效的方法是使用 .every
,它会在错误的情况下短路.
A more efficient way to do this would be to use .every
which will short circuit in falsy cases.
arr1.every(elem => arr2.indexOf(elem) > -1);
这篇关于在 JavaScript/CoffeeScript 中确定一个数组是否包含另一个数组的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文