在 ES6 Set 中存储数组并按值访问它们 [英] Storing arrays in ES6 Set and accessing them by value

查看:17
本文介绍了在 ES6 Set 中存储数组并按值访问它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种简单的方法来验证 ES6 Set 是否包含一个特定数组的值?我想要一个不需要我使用参考的解决方案:

Is there a simple way to verify that an ES6 Set contains a value that is a particular array? I'd like a solution that doesn't require me to use a reference:

var set = new Set();

var array = [1, 2];
set.add(array);
set.has(array); // true

set.add([3, 4]);
set.has([3, 4]); // false

到目前为止,我的解决方案是将所有内容存储为字符串,但这很烦人:

So far my solution is to store everything as a string, but this is annoying:

set.add([3, 4].toString());
set.has([3, 4].toString()); // true

推荐答案

没有没有.

Set 适用于对象和基元,可用于防止相同的基元和重新添加相同的对象实例.

A Set works on objects and primitives and is useful for preventing identical primitives and re-adding the same object instance.

每个数组都是它们自己的对象,因此您实际上可以添加具有相同值的两个不同数组.

Each array is their own object, so you can actually add two different arrays with the same values.

var set = new Set();
set.add([3, 4]);
set.add([3, 4]);
console.log(set.size);//2

此外,没有什么可以阻止对象在集合中被更改一次.

Additionally, there's nothing to prevent an object from being changed once in a set.

var set = new Set();
var a1 = [3, 4];
var a2 = [3, 4];
set.add(a1);
set.add(a2);
a2.push(5);
for (let a of set) {
    console.log(a);
}
//Outputs:
// [3, 4]
// [3, 4, 5]

集合没有检查集合中对象值的机制.由于对象的值可能随时发生变化,因此它不会比自己简单地循环更有效.

A set does not have a mechanism for checking the values of objects in a set. Since the value of an object could change at any time, it wouldn't be much more efficient than simply looping over them yourself.

您正在寻找的功能已在各种 ECMAScript 提案中使用,但似乎不会很快推出.

The functionality you are looking has been kicked around in various ECMAScript proposals, however it does not appear to be coming anytime soon.

这篇关于在 ES6 Set 中存储数组并按值访问它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆