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
197 views
in Technique[技术] by (71.8m points)

javascript - Using Array objects as key for ES6 Map

I am trying to update my code to ES6 as I am using Node 4.0 and really like its features so far. However I have problems with the new ES6 Map data structure as it behaves differently to {} when using Array as a key. I am using it as a counter map.

I run this code and I would like to know how I can use arrays as keys for the Map.

"use strict";

var a = new Map();
a.set(['x','y'], 1);
console.log(a.get(['x','y']));

var b = {};
b[['x','y']] = 1;

console.log(b[['x','y']]);

It prints out the following and the first line should be 1 and not undefined:

undefined
1

The original JS map stringifies the key and I am not wanting to do the same type of stringify hack with the new ES6 Map.

What can I do to use arrays as keys reliably for a ES6 Map?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Understand that ES2015 Map keys are compared (almost) as if with the === operator. Two array instances, even if they contain the same values, do not ever compare as === to each other.

Try this:

var a = new Map(), key = ['x', 'y'];
a.set(key, 1);
console.log(a.get(key));

Since the Map class is intended to be usable as a base class, you could implement a subclass with an overriding .get() function, maybe.

(The "almost" in the first sentence is to reflect the fact that Map key equality comparison is done via Object.is(), which doesn't come up much in daily coding. It's essentially a third variation on equality testing in JavaScript.)


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

...