javascript函数式编程05-高阶函数(Array.map())

吐槽君 分类:javascript

这是我参与更文挑战的第5天,活动详情查看: 更文挑战

紧跟上一篇 ,这一篇主要了解高阶函数(Array.map())

什么是map?

  • map()方法是一个数组的高阶函数,接受一个带有返回值的函数,使得数组的每一个元素都会调用这个指定的方法后形成一个新数组,但不改变原数组。
   let peoples = [
       {name:'lilei',age: 16},
       {name:'hanmeimei',age: 3},
       {name:'xiaoming',age: 5},
       {name:'tiantian',age: 8},
       {name:'xiaosong',age: 9},
   ]
   let agesArray = peoples.map(item => return item.age*2);
   // [32, 6, 10, 16, 18]
 

语法&参数说明

   array.map(function(currentValue,index,arr), thisValue)
 

aa2875404912.jpg

map函数的实现

//map接收一个数组arr和一个函数fn
function map(arr, fn) { 
let idx = -1, //表示每次循环的数组下标
	len = arr.length,
	result = new Array(len); 
	//这是我们要返回的新的数组,它的长度和arr一样

while (++idx < len) {
	result[index] = fn(arr[idx], idx, arr);
	//应用函数fn到数组中的每一个元素,再把结果放入数组中
	//后面的idx, arr也放进arguments中
	}
	return result;
}

 

map函数的应用

  • 格式化字符串
 let newStr = Array.prototype.map.call('new String', x => x + '*')
 console.log(newStr); //["n*", "e*", "w*", " *", "S*", "t*", "r*", "i*", "n*", "g*"]

//number转字符串
var arrNum = [1, 2, 3, 4, 5, 6, 7, 8, 9];
arrNum.map(String); // ['1', '2', '3', '4', '5', '6', '7', '8', '9']

 
  • 取数组对象中的某一个特定参数
let peoples = [
       {name:'lilei',age: 16},
       {name:'hanmeimei',age: 3},
       {name:'xiaoming',age: 5},
       {name:'tiantian',age: 8},
       {name:'xiaosong',age: 9},
   ]
   let agesArray = peoples.map(item => return item.age);
   // [16, 3, 5, 8, 9]
 
  • 格式化数组中的对象
    let kvArray =  [
              {key: 1, value: 10}, 
   		 {key: 2, value: 20}, 
              {key: 3, value: 30}
              ];
    let newArr = kvArray.map(item => {
       let obj = {}
       obj[item.key] = item.value
       return obj
   })
  	// newArr2 是 newArr 的简写形式
    let newArr2 = kvArray.map(item=>({[item.key]:item.value}))
    console.log(newArr); //[Object { 1: 10 }, Object { 2: 20 }, Object { 3: 30 }]
    console.log(newArr2,'00');//[Object { 1: 10 }, Object { 2: 20 }, Object { 3: 30 }] "00"
 

注意

  • map()不会对空数组进行检测
  • map()不会改变原始数组

回复

我来回复
  • 暂无回复内容