javascript
中的map()
方法用于返回一个新数组。
基本的语法:array.map(function(currentValue,index,arr), thisValue)
.
JS中的其他四种的数组迭代方法,他们都接受2个参数,第二个参数thisValue
为可选,代表着运行函数function(currentValue,index,arr)
时的作用域对象
array.some(function(currentValue, index, arr), thisValue);
array.every(function(currentValue, index, arr), thisValue);
array.filter(function(currentValue, index, arr), thisValue);
array.forEach(function(currentValue, index, arr), thisValue);
【es6新增】array.find(function(currentValue, index, arr),thisValue)
thisValue
作为该执行回调时使用,传递给函数,用作 “this
” 的值。
如果省略了 thisValue
,”this
” 的值为 “undefined
“.
实例:
var obj = {name:1};
var n = ["1"].map(function (t) {
console.log(this.name) //结果是1,this指向obj
},obj);
*也可以用bind实现。
var obj = {name:1};
var n = ["1"].map(function (t) {
console.log(this.name) //结果是1,this指向obj
}.bind(obj));
bind()
方法创建一个新的函数, 当被调用时,将其this
关键字设置为提供的值,在调用新函数时,在任何提供之前提供一个给定的参数序列。
var arr = [1];
var a = {
customObj: function() {
arr.map(function(){
//this指向a
}, this)
}
}
array.map(function(){
// this指向window/global
}, this)
(function () {
console.log(this.a); //输出1,this指向{a:1}
}.bind({
a:1
})());
或者
!function () {
console.log(this.a); //输出1,this指向{a:1}
}.bind({
a:1
})();
bind
, call
, apply
的作用都是让函数里面的this
指向给定的一个对象。
bind
扩展:
语法:fun.bind(thisArg[, arg1[, arg2[, ...]]])
thisArg
当绑定函数被调用时,该参数会作为原函数运行时的 this 指向。当使用new 操作符调用绑定函数时,该参数无效。
arg1, arg2, ...
当绑定函数被调用时,这些参数将置于实参之前传递给被绑定的方法。
!function () {
console.log(arguments);
//输出arguments为一个数组 => [Array(2), callee: ƒ, Symbol(Symbol.iterator): ƒ]
//Array(2) => ["test", "test2"]
}.bind({
a:1
},['test','test2'])();