确定一个数组是否包含JavaScript / CoffeeScript中另一个数组的内容 [英] Determining whether one array contains the contents of another array in JavaScript/CoffeeScript

查看:135
本文介绍了确定一个数组是否包含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


推荐答案

做一个ad-hoc数组交集并检查长度。

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 falsey case。

A more efficient way to do this would be to use .every which will short circuit in falsey cases.

arr1.every(elem => arr2.indexOf(elem) > -1);

这篇关于确定一个数组是否包含JavaScript / CoffeeScript中另一个数组的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆