javascript map用法实例

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chongchong1325/article/details/78295569

map() 方法创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。也就是原数组“映射”成对应新数组,调用的函数就是映射函数。

map()内部实现:

Array.prototype.map = function(fun /*, thisp*/)
{
  var len = this.length;
  if (typeof fun != "function")
    throw new TypeError();

  var res = new Array(len);
  var thisp = arguments[1];
  for (var i = 0; i < len; i++)
  {
    if (i in this)
      res[i] = fun.call(thisp, this[i], i, this);
  }

  return res;
};

具体实例:

1.普通数组:

var data = [1, 2, 3, 4];
var  newData = data.map(function(i){return i*i});
console.log(newData)
结果:[1, 4, 9, 16]

2.json数组

var json = [
{"id":21202,"bondId":21202,"market":"上交所","hypCode":"shzfz01","hypAbb":"上海政府债01","enterDate":"2014-05-14","createTime":1506756153000,"updateTime":1506756153000,"operator":"admin"},
{"id":21203,"bondId":21202,"market":"北金所","hypCode":"shzfz01","hypAbb":"上海政府债01","enterDate":"2014-05-16","createTime":1506756153000,"updateTime":1506756153000,"operator":"admin"}];
var newJson = json.map((us)=>{
return {newbondId:us.bondId,newmarket:us.market,newhypCode:us.hypCode}
});
console.log(newJson);

结果:
    1. [{newbondId:21202,
    2. newhypCode:"shzfz01",
    3. newmarket:"上交所"},

    1. {newbondId:21202,
    2. newhypCode:"shzfz01",
    3. newmarket:"北金所"}]





没有更多推荐了,返回首页