您是否遇到过[].slice.call(arguments)
或Array.prototype.slice.call(arguments)
在任何 JavaScript 代码中?
这个令人困惑的代码用于将具有.length
属性和数字索引的参数对象(就是所谓的类数组对象)转换为真正的数组,该数组调用两种方法:slice()
和call()
slice()
用法:
slice(beginIndex)
slice(beginIndex, endIndex)
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice()); // [ 'ant', 'bison', 'camel', 'duck', 'elephant' ]
console.log(animals.slice(2)); // ["camel", "duck", "elephant"]
console.log(animals.slice(2, 3)); // [ 'camel' ]
call()
用法:
call()
call(thisArg)
call(thisArg, arg1)
call(thisArg, arg1, arg2)
call(thisArg, arg1, ... , argN)
function Product(name, price) {
this.name = name;
this.price = price;
}
function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}
console.log(new Food('cheese', 5).name); // cheese
因此,如果我们将this
的值指定slice()
给一个类似数组的对象,
我们就可以使slice()
该方法在该对象上工作,并且如果我们在slice()
没有传递可选参数的情况下调用,它将把整个块作为一个新数组返回。
let listObj = {
'0': 'zero',
'1': 'one',
'2': 'two',
length: 3
};
let arr = [].slice.call(listObj);
console.log(arr); // [ 'zero', 'one', 'two' ]