1.map()方法
map 方法返回每次函数调用结果组成的数组。
array.map(function(currentValue, index, arr), thisIndex)
let array = [1, 2, 3, 4, 5];
let newArray = array.map((item) => {
return item * item;
})
console.log(newArray) // [1, 4, 9, 16, 25]
let array = [1, 2, 3, 4, 5];
let newArray = array.map((_,index) => {
return index;//返回下标
})
console.log(newArray) //[0,1,2,3,4]
map()注意点:
map不会对空数组进行检测
map不会改变原始数组
2.forEach()的定义和用法
1.forEach()方法用于调用数组的每个元素,并将元素传递给回调函数。
2.forEach()有两个参数,第一个是function()函数,第二个是对象;
3.函数里面有三个参数,第一个是数组的每一项值(必选),第二个是数组下标(可选),第三个是原数组(可选)
4.forEach()第二个参数对象,使第一个参数函数的this指向对象
var obj = {
'1' : 'abc',
'3' : 100,
'5' : 'hello'
}
var arr = [1, 3, 5];
arr.forEach(function(item){
// console.log(item);
},obj);//返回值: 1 3 5
var obj = {
'1' : 'abc',
'3' : 100,
'5' : 'hello'
}
var arr = [1, 3, 5];
arr.forEach(function(item, index, self){
console.log(index);
},obj);//返回值:0 1 2
3.map和forEach的区别
1.map有返回值,可以开辟新空间,return出来一个length和原数组一致的数组,即便数组元素是undefined或者是null。
2.forEach默认无返回值,返回结果为undefined,可以通过在函数体内部使用索引修改数组元素。
3.map的处理速度比forEach快,而且返回一个新的数组,方便链式调用其他数组新方法