美文网首页
ES5-Array-map

ES5-Array-map

作者: chrisghb | 来源:发表于2019-06-10 22:23 被阅读0次

参考文章:Array 对象


map方法将数组的所有成员依次传入参数函数,然后把每一次的执行结果组成一个新数组返回。

map方法会给原数组中的每个元素都按顺序调用一次 callback 函数。callback 每次执行后的返回值(包括 undefined)组合起来形成一个新数组

  • 所以,回调函数必须要return返回值。如果没有,就像下面这样:
var data = [1, 2, 3, 4];
var arrayOfSquares = data.map(function() {});

arrayOfSquares.forEach(console.log);
//0 (4) [undefined, undefined, undefined, undefined]
//1 (4) [undefined, undefined, undefined, undefined]
//2 (4) [undefined, undefined, undefined, undefined]
//3 (4) [undefined, undefined, undefined, undefined]

结果如下图,可以看到,数组所有项都被映射成了undefined:

如果数组遍历的目的是为了得到返回值,那么使用map方法,否则使用forEach方法。

作用

原数组被“映射”成对应新数组

语法

array.map(function(currentValue,index,arr), thisValue)
参数 描述
currentValue 必需。当前元素
index 可选。当前元素的索引值。
arr 可选。当前元素所属的数组对象。
thisValue 可选。绑定参数函数的this变量。

回调函数语法:

var numbers = [1, 2, 3];

numbers.map(function (n) {
  return n + 1;//n当前元素
});
// [2, 3, 4]

numbers
// [1, 2, 3]

上面代码中,numbers数组的所有成员依次执行参数函数,运行结果组成一个新数组返回。

  • 注意: map() 不会改变原始数组。
[1, 2, 3].map(function(elem, index, arr) {
  return elem * index;
});
// [0, 2, 6]

上面代码中,map方法的回调函数有三个参数,elem为当前成员的值,index为当前成员的位置,arr为原数组([1, 2, 3])。

上下文参数

map方法还可以接受第二个参数,用来绑定回调函数内部的this变量。

var arr = ['a', 'b', 'c'];

[1, 2].map(function (e) {
  return this[e];
}, arr)//arr替换this
// ['b', 'c']

上面代码通过map方法的第二个参数,将回调函数内部的this对象,指向arr数组。

如果数组有空位,map方法的回调函数在这个位置不会执行,会跳过数组的空位。

var f = function (n) { return 'a' };

[1, undefined, 2].map(f) // ["a", "a", "a"]
[1, null, 2].map(f) // ["a", "a", "a"]
[1, , 2].map(f) // ["a", , "a"]

上面代码中,map方法不会跳过undefined和null,但是会跳过空位

Array.prototype扩展可以让IE6-IE8浏览器也支持map方法:

if (typeof Array.prototype.map != "function") {
  Array.prototype.map = function (fn, context) {
    var arr = [];
    if (typeof fn === "function") {
      for (var k = 0, length = this.length; k < length; k++) {      
         arr.push(fn.call(context, this[k], k, this));
      }
    }
    return arr;
  };
}

相关文章

  • ES5-Array-map

    参考文章:Array 对象 map方法将数组的所有成员依次传入参数函数,然后把每一次的执行结果组成一个新数组返回。...

网友评论

      本文标题:ES5-Array-map

      本文链接:https://www.haomeiwen.com/subject/fuhxfctx.html