Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

javascript - Storing arrays in ES6 Set and accessing them by value

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No there is not.

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...