ES6终于加入了高级的数据结构集合,包括Map,WeakMap,Set,WeakSet等,并且都是iterable的,可以用spread操作符和for...of语法遍历。这些数据结构在其他语言中早就有了,使用起来也非常方便,这篇文章从Map讲起。规范的23.1章节定义了Map以及相关的API,有兴趣的自己去看。
有人会说JS中的Object实质上不就是个Map吗?没错,但Object有个问题就是它的key都是字符串,ES6中也可以用Symbol做key。但Map没有这个限制,key可以是任意类型。
1)构造函数Map ( [ iterable ] )
let map = new Map([
[ 1, 'one' ],
[ 2, 'two' ],
[ 3, 'three' ]
]);
2)Map.prototype.get ( key )
如果集合中有key,返回value,否则返回undefined
let map = new Map();
const KEY1 = {};
map.set(KEY1, 'hello');
console.log(map.get(KEY1)); // hello
console.log(map.get(0));//undefined
3)Map.prototype.set ( key , value )
给Map设置值,如果已经存在key,则更新value,如果不存在key,创建一条记录。返回本身,可以链式操作
let map = new Map()
.set(1, 'one')
.set(2, 'two')
.set(3, 'three');
检查Map是否存在key,存在返回true,不存在返回false
5)Map.prototype.delete ( key )
删除key对应的记录,如果存在key,返回true,否则返回false
6)Map.prototype.clear ( )
清空所有记录
7)Map.prototype.entries(),Map.prototype.keys(),Map.prototype.values()
用过Java Map的人肯定对这些不陌生。返回的依次是:所有记录,键,值,都是可以iterable的。但注意返回的不是个数组。
var map = new Map();
const KEY1 = {};
map.set(KEY1, 'hello');
map.values()[0]//undefined
[...map.values()][0]//"hello"
8)Map.prototype.size
返回记录数,回调参数为value,key,map
9)Map.prototype.forEach
不多说了,谁都会用
最后我们要弄清一个问题,Map的key是如何确定唯一性的。看规范Map章节的一开始就有个描述:
Map objects are collections of key/value pairs where both the keys and values may be arbitrary ECMAScript language values. A distinct key value may only occur in one key/value pair within the Map’s collection. Distinct key values are discriminated using the SameValueZero comparison algorithm.
继续看SameValueZero的定义,规范7.2.10章节SameValueZero(x, y):
1. ReturnIfAbrupt(x).
2. ReturnIfAbrupt(y).
3. If Type(x) is different from Type(y), return false.
4. If Type(x) is Undefined, return true.
5. If Type(x) is Null, return true.
6. If Type(x) is Number, then
a. If x is NaN and y is NaN, return true.
b. If x is +0 and y is -0, return true.
c. If x is -0 and y is +0, return true.
d. If x is the same Number value as y, return true.
e. Return false.
7. If Type(x) is String, then
a. If x and y are exactly the same sequence of code units (same length and same code units at corresponding indices) return true; otherwise, return false.
8. If Type(x) is Boolean, then
a. If x and y are both true or both false, return true; otherwise, return false.
9. If Type(x) is Symbol, then
a. If x and y are both the same Symbol value, return true; otherwise, return false.
10. Return true if x and y are the same Object value. Otherwise, return false.
简单来看和全等===差不多,只不过NaN是等于NaN,并且正0和负0也相等
*以上全部代码在Chrome 47下通过测试