官方给的解释:
**map()**
方法创建一个新数组,其结果是该数组中的每个元素是调用一次提供的函数后的返回值。
代码示例:
let arr = [1,2,3];
let obj = {
a:1
}
arr.map((val, index ,arr) => {
console.log(val) // 当前值
console.log(index) // 当前索引
console.log(arr) // 遍历的数组
})
语法:
var new_array = arr.map(function callback(currentValue[, index[, array]]) {
// Return element for new_array
}[, thisArg])
重点研究一下第二参数 thisArg
官方解释 :
thisArg
可选执行 callback
函数时值被用作this
。
这里的意思是这个 thisArg
对象可以在callback函数中访问,这里有一个小坑,如果想要访问这个 thisArg
对象的话,只能使用 es5 函数方式
let arr = [1,2,3];
let obj = {
a:1
}
// 正确示例
arr.map(function(val){
console.log(this) // { a:1 }
}, obj)
// 错误示例
arr.map((val) => {
console.log(this) // window 对象
}, {a:1})
这是因为,箭头函数没有 不能绑定 this, 会捕获其所在的上下文的this值,作为自己的this值。