迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript 中检查 Set 是否包含数组

作者:迹忆客 最近更新:2022/11/17 浏览次数:

使用 has() 方法检查 Set 是否包含数组,例如 set.has(arr)。 必须通过对 has 方法的引用来传递数组以获得可靠的结果。 has 方法测试 Set 中是否存在某个值,如果该值包含在 Set 中则返回 true。

const arr = ['one'];

const set1 = new Set([arr, ['two']]);

console.log(set1.has(arr)); // 👉️ true

我们通过引用 Set.has 方法传递了一个数组,以检查该数组是否包含在 Set 中。

请注意 ,数组必须通过引用传递给 has 方法。 按值传递数组是行不通的。

const arr = ['one'];

const set1 = new Set([arr, ['two']]);

console.log(set1.has(['one'])); // 👉️ false

这是因为我们正在检查的数组在内存中的不同位置并且具有完全不同的引用。

如果我们没有对要检查的数组的引用,则可以使用 for...of 循环遍历 Set 并检查特定数组的存在。

const set1 = new Set([['one', 'two'], ['three']]);

let containsArray = false;
const checkForArr = ['one', 'two'];

for (const arr of set1) {
  if (arr.toString() === checkForArr.toString()) {
    containsArray = true;
    break;
  }
}

console.log(containsArray); // 👉️ true

我们初始化了一个 containsArray 变量并将其设置为 falsefor...of 循环允许我们遍历 Set 并检查特定数组是否包含在其中。

我们使用 Array.toString() 方法来获取包含数组元素的字符串。 仅当两个数组具有相同顺序的相同元素时,这才会评估为真。

console.log(['one', 'two'].toString()); // 👉️ "one,two"

// 👇️ true
console.log(
  ['one', 'two'].toString() === ['one', 'two'].toString()
);

// 👇️ false
console.log(
  ['one', 'two'].toString() === ['two', 'one'].toString()
);

如果找到数组,我们使用 break 关键字退出循环并避免不必要的工作。

有一种方法可以让我们获得对数组的引用,使用 has 方法性能更高,尤其是当数组接近 Set 的末尾或根本不包含在 Set 中时。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

JavaScript POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便