JS的map方法和Map对象

map方法 Array.prototype.map()

语法:

array.map(function(item,index,arr), thisValue)

  • item:数组每一项 (必须)
  • index:每项索引 (可选)
  • arr:数组本身 (可选)
  • thisValue:修改循环时的this指向,默认全局对象 (可选)

注意点:

  1. map是生成一个新数组,不适用返回的新数组是违背设计初衷,请用forEach或者for-of,基于设计初衷,使用map时,写出return
  2. map不会改变原数组,但是可以在回调中改变
  3. 空数组不会调用map
var arrA = [1, 2, 3, 4];
var b = 1;
arrA.map(function(item, index, arr){
    console.log(item, index, arr, this)
    return item++;
}, b)

输出:
1 0 (4) [1, 2, 3, 4] Number {1}
2 1 (4) [1, 2, 3, 4] Number {1}
3 2 (4) [1, 2, 3, 4] Number {1}
4 3 (4) [1, 2, 3, 4] Number {1}

Map对象

Map 对象存有键值对,其中的键可以是任何数据类型。
Map 对象记得键的原始插入顺序。
Map 对象具有表示映射大小的属性。

基本的 Map() 方法:

  • new Map() 创建新的 Map 对象。
  • set() 为 Map 对象中的键设置值。
  • get() 获取 Map 对象中键的值。
  • entries() 返回 Map 对象中键/值对的数组。
  • keys() 返回 Map 对象中键的数组。
  • values() 返回 Map 对象中值的数组。
  • Map.clear() 从 Map 中移除所有元素

Map()属性

size: 数量

//单个键值对
let map = new Map();
let child = { name:'李狗蛋' };
map.set(child, [1, 2, 3])  //存储
map.get(child)  // [1,2,3]   获取
map.has(child) //true     判断是否存在
map.delete(child)   //true   删除

//多个键值对
let map = new Map([
    ['a', 123],
    ['b', 456]
]);

map.get('b')   //456
map.size // 2
map.clear();  //清空

你可能感兴趣的:(JavaScript,javascript)