今天做题的时候看题解用到了JS里的Map
对象,并且利用了ES6的新特性,因为之前没学过,特地做一下笔记
ES5及以前的Map
只支持“字符串-值”这种集合,ES6支持“值-值”的集合,是一种更合理的Hash结构。
Map
的相关方法:
const map = new Map([
['name', '张三'],
['title', 'Good']
])
map.size // 2
map.has('name') // true
map.get('name') // '张三'
map.delete('name')
map.has('name') // false
map.set('sex', '女')
map.has('sex') // true
map.get('sex') // '女'
// get不存在的键会返回undefined
map.clear() // 清除所有成员
// 已实例化的Map对象可以作为new Map()构造方法的参数:
const map2 = new Map(map)
以上是一些基本操作。
下面是遍历方法:
keys() // 返回所有键名的遍历器
values() // 返回所有值的遍历器
entries() // 返回所有成员的遍历器
forEach() // 遍历Map的所有成员
for (let key of map.keys())
for(let value of map.values())
for(let item of map.entries()) // item[0] 和 item[1] 分别代表键和值
for(let [key, value] of map.entries()) // 同上
for(let [key, value] of map) // 同上
// Map结构的默认遍历器接口就是entries
map[System.iterator] === map.entries // true
map.forEach(function(value, key, map) {
console.log('key = ' + key + ', ' + 'value = ' + value)
})
// 其可以接受第二个参数来绑定this
const reporter = {
report: function(key, value) {
console.log('key = ' + key + ', ' + 'value = ' + value)
}
}
map.forEach(function(value, key, map) {
this.report(key, value)
}, reporter)
// 这里的this就指向了reporter
下面是力扣里的题:
涉及到深搜(dfs)的知识
1319.联通网络的操作次数