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

编程入门 行业动态 更新时间:2024-10-25 11:34:46
本文介绍了检查数组是否包含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));

更多推荐

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

本文发布于:2023-11-22 15:16:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617936.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!