JavaScript 中检查 Set 是否包含数组
使用 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
变量并将其设置为 false。 for...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 中时。
相关文章
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 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。