ES6学习——集合(Collections):Map API

73 篇文章 23 订阅

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');


4)Map.prototype.has ( key )

检查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下通过测试

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值