使用 Array 对象作为 ES6 Map 的键 [英] Using Array objects as key for ES6 Map

查看:26
本文介绍了使用 Array 对象作为 ES6 Map 的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的代码更新为 ES6,因为我使用的是 Node 4.0 并且目前非常喜欢它的功能.但是,我对新的 ES6 Map 数据结构有问题,因为当使用 Array 作为键时,它的行为与 {} 不同.我将其用作计数器地图.

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.

我运行这段代码,我想知道如何使用数组作为 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 而不是 undefined:

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

undefined
1

原始 JS 映射将键字符串化,我不想使用新的 ES6 Map 进行相同类型的字符串化破解.

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 (almost) 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.

(第一句中的几乎"是为了反映Map键相等比较是通过Object.is()来完成的,在日常编码中很少出现.它是本质上是 JavaScript 中相等性测试的第三变体.)

(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.)

这篇关于使用 Array 对象作为 ES6 Map 的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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