检查数组是否包含JavaScript中的数组

问题描述:

javascript includes 函数可用于查找数组中是否存在元素.请看以下示例:

The javascript includes function can be used to find if an element is present in an array. Take the following example:

var arr = ['hello', 2, 4, [1, 2]];

console.log( arr.includes('hello') );
console.log( arr.includes(2) );

console.log( arr.includes(3) );

console.log( arr.includes([1, 2]) );

'hello' 2 传递给函数将返回 true ,因为两者都存在于数组 arr 中>.

Passing 'hello' or 2 to the function returns true, as both are present in the array arr.

3 传递给该函数将返回 false ,因为它不存在于数组中.

Passing 3 to the function returns false because it is not present in the array.

但是,为什么 arr.includes([1,2])也会返回 false ,即使它等于数组中的最后一个元素也是如此?如果此方法不起作用,我还能如何查找我的数组是否包含 [1、2] 项?

However, why does arr.includes([1, 2]) return false as well, even though this is equal to the last element in the array? And if this method does not work, how else can I find whether my array includes the item [1, 2]?

Array#includes 通过浅层比较进行检查,因此在您的情况下,字符串和数字为基元它们只有一个实例,因此您可以从 Array#includes 中获得 true .

The Array#includes checks by shallow comparison, so in your case the string and numbers are primitives there is only ever a single instance of them so you get true from Array#includes.

但是,当您检查数组时,您传递的是一个新的数组实例,该实例与您要检查的数组中的实例不同,因此浅层比较失败.

But when you check for array, you are passing a new array instance which is not the same instance in the array you are checking so shallow comparison fails.

要检查一个数组是否包含在另一个数组中,请首先检查它是否是一个数组,然后在两个数组之间进行深入比较.

To check for an array is included in another array first check if it is an array then do a deep comparison between the arrays.

  • 请注意,以下代码段仅适用于 基元数组 :

var arr = ['hello', 2, 4, [1, 2]];
const includesArray = (data, arr) => {
  return data.some(e => Array.isArray(e) && e.every((o, i) => Object.is(arr[i], o)));
}

console.log(includesArray(arr, [1, 2]));

但是,如果您保留对数组 [1、2] 的引用,并使用该引用进行搜索,则 Array#includes 会起作用,因为在这种情况下,浅表比较会完美地起作用(请遵守同值零算法):

But if you keep the reference to the array [1, 2] and search with the reference the Array#includes works as in this case the shallow comparison works perfectly (obeying same value zero algorithm):

const child =  [1, 2];
const arr = ['hello', 2, 4, child];

console.log(arr.includes(child));