使用Array对象作为ES6 Map的键 [英] Using Array objects as key for ES6 Map
问题描述
我正在尝试将我的代码更新为ES6,因为我使用的是Node 4.0,并且到目前为止它非常喜欢它的功能。但是我在新的ES6 Map
数据结构时遇到问题,因为当使用<$ c $时,它与 {}
的行为不同c>数组作为密钥。我使用它作为计数器地图。
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']]);
打印出以下内容,第一行应为 1
而不是未定义
:
It prints out the following and the first line should be 1
and not undefined
:
undefined
1
原始的JS地图将字符串化,我不想做同样类型的stringify hack使用新的ES6 地图
。
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
.
如何将数组作为密钥可靠地用于ES6 Map
?
What can I do to use arrays as keys reliably for a ES6 Map
?
推荐答案
了解ES2015 Map键与 ===
运算符进行比较。两个数组实例,即使它们包含相同的值,也不会相互比较为 ===
。
Understand that ES2015 Map keys are compared as if with the ===
operator. Two array instances, even if they contain the same values, do not ever compare as ===
to each other.
试试这个:
var a = new Map(), key = ['x', 'y'];
a.set(key, 1);
console.log(a.get(key));
由于Map类可用作基类,因此可以实现一个子类,覆盖 .get()
函数,也许。
Since the Map class is intended to be usable as a base class, you could implement a subclass with an overriding .get()
function, maybe.
这篇关于使用Array对象作为ES6 Map的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!