JavaScript中的map()方法详解
map()方法经常拿来遍历数组,但是不改变原数组,但是会返回一个新的数组,并且这个新的数组不会改变原数组的长度
注意:有时候会出现这种现象,出现几个undefined
const array = [1, 4,9, 16]
console.log("原数组array为",array)
const map = array.map(x => {
if (x > 5) {
return x
}
})
//返回[undefined,undefined,9,16]
其实,map()方法是对每一项数组进行遍历,遍历一次,返回一个值,给新数组加上一个元素,这是就是满足x=4的元素,只有两个,所以其他项就返回了undefined。
map方法的实现
Array.prototype.fakeMap = function(fn,context) {
let arr = this;
let temp = [];
for(let i=0;i<arr.length;i++){
let result = fn.call(context,arr[i],i,arr);
temp.push(result);
}
return temp;
}