【循环系列】之map循环

2,210 阅读1分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

前言

发现JS中的循环有好多,如果让一下说出来,感觉有些会想不起来,本次花时间来梳理一下JS中循环语句。

本系列相关文章:

  1. 【循环系列】for循环和while循环
  2. 【循环系列】for in和forEach循环

本文是本系列第3篇,关于map循环

map循环

mapforEach非常相似

map接受的参数跟forEach一模一样,第一个参数是回调函数,第二个是this指向,而且回调函数中的参数也是一样。

正常情况下,map需要配合return,返回是一个新的数组;若是没有return,用法相当于forEach

所以map常常用于重新整理数组里头的数据结构,如下伪代码:

let arr = [
   {title:'aaaaa', read:100, hot:true},
   {title:'bbbb', read:100, hot:true},
   {title:'cccc', read:100, hot:true},
   {title:'dddd', read:100, hot:true}
];
let newArr = arr.map((item, index, arr)=>{
   let json={}
   json.t = `^_^${item.title}-----`;
   json.r = item.read+200;
   json.hot = item.hot == true && '真棒!!!';
   return json;
});
console.log(newArr);

打印结果

下面再来模拟封装一下_map

Array.prototype._map = function(fn,thisTo){
	let res = []
	for(let i = 0;i<this.length;i++){
		res[i] = fn.call(thisTo,this[i],i,this)
	}
	return res;
}
//test code
let arr = [
   {title:'aaaaa', read:100, hot:true},
   {title:'bbbb', read:100, hot:true},
   {title:'cccc', read:100, hot:true},
   {title:'dddd', read:100, hot:true}
];
let newArr = arr._map((item, index, arr)=>{
   let json={}
   json.t = `^_^${item.title}-----`;
   json.r = item.read+200;
   json.hot = item.hot == true && '真棒!!!';
   return json;
});
console.log(newArr);

实现成功

结束

以上就是map循环的相关内容