map()
方法创建一个新数组,这个新数组由原数组中的每个元素都调用一次提供的函数后的返回值组成。
- map不改变原数组
- map返回数组元素操作后的值,就是一定有返回值
- map遍历一次产生一个返回值
const array1 = [1, 4, 9, 16];
const map1 = array1.map(x => x * 2);
console.log(map1);
// output: Array [2, 8, 18, 32]
再看下面一个例子
const array1 = [1, 4, 9, 16];
const map1 = array1.map((item)=>{
if(item === 4){
return item * 2
}
});
console.log(map1);
// output: Array [undefined, 8, undefined, undefined]
为什么会出现undefined呢,自己手写一个map方法感受一下
const a = [1, 2, 3]
//自定义map函数
//fn为传入的处理函数
function MyMap(fn) {
const b = []
//this为调用的数组
for (let i = 0; i < this.length; i++) {
const data = fn(this[i])
b.push(data)
}
return b
}
//把函数挂在到Array的原型上
Array.prototype.MyMap = MyMap
const res = a.MyMap(item => item += 2)
console.log(res)
// output: Array [3, 4, 5]
总结
这样就能看出来为什么会出现undefined,当MyMap没有得到处理的返回值或返回undefined时就会push(undefined)进去。
可以猜猜这个会返回啥😄
let a = [1,2,3];
a = a.map((item) => {
item +=2;
});
console.log(a);
//?