js map的初级使用方法

[].map(function(value, index, array) {
    // ...
});
.map映射 可以对数组进行遍历,使用方法和foreach类似
 
callback(即 函数function)必须要有return,否则报错undefined
 
通过Array.prototype   使map方法兼容ie6-ie8,代码如下
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;
  };
}
 

猜你喜欢

转载自www.cnblogs.com/wurui-0922/p/10106853.html
今日推荐