我正在编写几个采用不同类型参数的函数。因此,这样做要简单得多:
var myFunc = function() {
var args = Array.prototype.slice.call(arguments)
}
...而不是尝试直接在函数声明的参数字段中处理所有不同的可能性,例如:
var myFunc = function(param1, param2, param3) {
if (param3) {
// etc.
}
}
Array.prototype.slice.call(arguments)
虽然给代码增加了很多,但降低了可读性。我想弄清楚是否有一种方法可以编写一个辅助函数,它可以完成与 Array.prototype.slice.call()
相同的事情,但更清晰且更易于阅读。我正在尝试类似的东西:
var parseArgs = function() {
return Array.prototype.slice.call(arguments)
}
var foo = function() {
console.log(parseArgs(arguments))
}
foo('one', 'two', 'three')
// [Arguments, ['one', 'two', 'three']]
但显然那是行不通的。
最佳答案
如果你不想每次都写Array.prototype.slice.call(args)
,你可以这样做:
var slice = Function.call.bind(Array.prototype.slice);
然后你可以在任何地方使用它,比如:
function fn(){
var arr = slice(arguments);
}
关于javascript - 更简洁的处理方式 Array.prototype.slice.call(arguments),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34797268/