Map对象


let map = new Map();
let item = { name: '惠芬儿' };
map.set(item, [1, 2, 3]); // 存储

map.get(item)  //[1, 2, 3] // 获取
map.has(item)  //true // 判断是否存在
map.delete(item)  //true  // 删除
map.has(item)  //false

// 还有另一种设置方式,通过数组来设置
map = new Map([
    ['first', 123],
    ['second', 456]
]);

map.get('first')   //123
map.get('seconf')  //456

// 注意:不能通过以下方式设置。

let wrongMap = new Map()
wrongMap['bla'] = 'blaa'
wrongMap['bla2'] = 'blaaa2'

console.log(wrongMap)  // Map { bla: 'blaa', bla2: 'blaaa2' }

wrongMap.has('bla')    // false
wrongMap.delete('bla') // false
console.log(wrongMap)  // Map { bla: 'blaa', bla2: 'blaaa2' }

Map的强大在于提供了很多实用方法

javascript中,对象本身就是一种Map结构。


var map = {};
map['key1'] = 1;
map['key2@'] = 2;
 
console.log(map['key1']);//结果是1.
console.log(map['key2@']);//结果是2.
 
//如果遍历map
for(var prop in map){
    if(map.hasOwnProperty(prop)){
        console.log('key is ' + prop +' and value is' + map[prop]);
    }
}

文章作者: iamfugui
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 iamfugui !
评论
  目录