从历史上看,我们必须这样做:
var args = Array.prototype.slice.call(arguments)
fn.apply(this, args);
获取实际的函数调用参数并将它们传递给 Function.prototype.apply 。然而,一段时间以来,我可以看到参数对象确实有可用的切片方法,因此不再需要上面的代码片段。
问题是 - 什么时候改变的,它是什么,规范更新?
编辑:我上面不清楚...我的意思是 fn.apply(this, argument)
确实有效(我检查了最新的 chrome 和 firefox):
function add(a,b){
return a + b;
}
function whatever(){
return add.apply(null, arguments)
}
whatever(2,3) // 5
换句话说,参数
现在可以直接在 apply 中使用。前段时间不行,必须像上面那样传给Array.prototype.slice.apply。
最佳答案
事实并非如此。
尝试以下操作:
var foo = function() {
console.log(Object.prototype.toString.call(arguments));
};
foo(); // [object Arguments]
console.log(Object.prototype.toString.call([])); // [object Array]
请注意,数组和对象之间的区别在 JS 领域有点模糊:
var foo = { "0": 1, "1": 2 };
Object.defineProperty(foo, "length", {
value: 2
});
foo
现在可以使用 call
、apply
等使用数量惊人的数组方法。
关于javascript - JS 函数中的参数什么时候变成了真正的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41879720/