我想要一个当且仅当给定数组包含给定“目标”数组的所有元素时返回 true
的函数。如下。
const target = [ 1, 2, 3, ];
const array1 = [ 1, 2, 3, ]; // true
const array2 = [ 1, 2, 3, 4, ]; // true
const array3 = [ 1, 2, ]; // false
我怎样才能完成上述结果?
最佳答案
您可以结合 .every()
和 .includes()
方法:
let array1 = [1,2,3],
array2 = [1,2,3,4],
array3 = [1,2];
let checker = (arr, target) => target.every(v => arr.includes(v));
console.log(checker(array2, array1)); // true
console.log(checker(array3, array1)); // false
关于javascript - 检查数组是否包含另一个数组的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53606337/