❀ forEach参数
arr.forEach(function(self,index,arr){},this);
self:数组当前遍历的元素,默认从左往右依次获取数组元素。
index:数组当前元素的索引,第一个元素索引为0,依次类推。
arr:当前遍历的数组。
this:回调函数中this指向。
❀ map参数
map() 返回一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。
let list = ["a", "b", "c"]
var str = list.map(function(item, index, list) {
console.log(this); //指向Window
console.log("原数组arr:", list); //注意这里执行5次
return item + item;
}, this);
console.log(str);
//输出结果是:["aa", "bb", "cc"]
箭头函数简写:
let list = ["a", "b", "c"]
var str = list.map(x=>x+x);
console.log(str);
//输出结果是:["aa", "bb", "cc"]
let list = [4, 9, 16]
var str = list.map(Math.sqrt);//开方
console.log(str);
//输出结果是: [2, 3, 4]
共同点:
- 1.都是循环遍历数组中的每一项。
- 2.forEach() 和 map() 里面每一次执行匿名函数都支持3个参数:数组中的当前项item,当前项的索引index,原始数组input。
- 3.匿名函数中的this都是指Window。
- 4.只能遍历数组。
1.forEach()
没有返回值。
var ary = [12,23,24,42,1];
var res = ary.forEach(function (item,index,input) {
input[index] = item*10;
})
console.log(res);//-->undefined;
console.log(ary);//-->会对原来的数组产生改变;
2.map()
有返回值,可以return 出来。
var ary = [12,23,24,42,1];
var res = ary.map(function (item,index,input) {
return item*10;
})
console.log(res);//-->[120,230,240,420,10];
console.log(ary);//-->[12,23,24,42,1];
forEach这种方法也有一个小缺陷:你不能使用break语句中断循环,也不能使用return语句返回到外层函数。
map遍历支持使用return语句,支持return返回值
运用
let list = ["a", "b", "c"]
let obj = {
name: "张三",
age: 30
}
list.forEach(function(value, index, arr) {
console.log(`我是原数组:${arr}: ${value}---${index} 我是this指向:${this.name}`)
}, obj)