首页 > 其他 > 详细

map( ) 方法

时间:2021-04-20 14:02:01      阅读:19      评论:0      收藏:0      [点我收藏+]

Array.prototype.map( )

  map( ) 方法创建一个新数组,其结果是该数组中的每个元素调用一次提供的函数后的返回值

 

语法:

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
 // Return element for new_array 
}[, thisArg])

 callback 生成新数组的函数,使用三个参数:

    currentValue

          callback 数组中当前正在处理的当前元素

          index 可选

               callback 数组中正在处理的当前元素的索引

          array 可选

               map方法调用的数组

 

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

因为map生成一个新的数组,当你不打算使用返回的新数组却使用map是违背设计初衷的,请用forEach或者for-of替代。

以下情况:你不该使用map

    1、你不打算使用返回的新数组

    2、或者从回调函数中不返回值

 

求数组中每个元素的平方根

var numbers = [1, 4, 9];
var roots = numbers.map(Math.sqrt);
// roots的值为[1, 2, 3], numbers的值仍为[1, 4, 9]

 

可能返回含undefined的数组

var numbers = [1, 2, 3, 4];
var filteredNumbers = numbers.map(function(num, index) {
  if(index < 3) {
     return num;
  }
});
//index goes from 0,so the filterNumbers are 1,2,3 and undefined.
// filteredNumbers is [1, 2, 3, undefined]
// numbers is still [1, 2, 3, 4]

 

map( ) 方法

原文:https://www.cnblogs.com/zhishiyv/p/14680022.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!