快速数组对象取值与数组映射新数组--array.map

array.map(callback,[ thisObject]);

1、map方法的作用不难理解,“映射”嘛,也就是原数组被“映射”成对应新数组

a)array.map(()=>值);

[1,2,3].map(()=>'2323')
(3) ["2323", "2323", "2323"]

b)array.map(p=>[值,p]);

2、可以利用map方法方便获得对象数组中的特定属性值们

var users = [
  {name: "张含韵", "email": "[email protected]"},
  {name: "江一燕",   "email": "[email protected]"},
  {name: "李小璐",  "email": "[email protected]"}
];

var emails = users.map(function (user) { return user.email; });

undefined
emails
(3) ["[email protected]", "[email protected]", "[email protected]"]

3、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;
  };

  

猜你喜欢

转载自www.cnblogs.com/yiyi17/p/10349776.html