最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cleaner way of handling Array.prototype.slice.call(arguments) - Stack Overflow

programmeradmin1浏览0评论

I'm writing several functions that take different types of parameters. As such, it's much simpler to just do:

var myFunc = function() {
    var args = Array.prototype.slice.call(arguments)
}

...than to try to handle all the different possibilities directly in the parameter field of the function declaration, e.g.:

var myFunc = function(param1, param2, param3) {
    if (param3) {
        // etc.
    }
}

Array.prototype.slice.call(arguments) adds a lot to the code though, and reduces readability. I'm trying to figure out if there's a way to write a helper function that could acplish the same thing as Array.prototype.slice.call(), but cleaner and easier to read. I was trying something like:

var parseArgs = function() {
    return Array.prototype.slice.call(arguments)
}

var foo = function() {
    console.log(parseArgs(arguments))
}

foo('one', 'two', 'three')
// [Arguments, ['one', 'two', 'three']]

But obviously that doesn't work.

I'm writing several functions that take different types of parameters. As such, it's much simpler to just do:

var myFunc = function() {
    var args = Array.prototype.slice.call(arguments)
}

...than to try to handle all the different possibilities directly in the parameter field of the function declaration, e.g.:

var myFunc = function(param1, param2, param3) {
    if (param3) {
        // etc.
    }
}

Array.prototype.slice.call(arguments) adds a lot to the code though, and reduces readability. I'm trying to figure out if there's a way to write a helper function that could acplish the same thing as Array.prototype.slice.call(), but cleaner and easier to read. I was trying something like:

var parseArgs = function() {
    return Array.prototype.slice.call(arguments)
}

var foo = function() {
    console.log(parseArgs(arguments))
}

foo('one', 'two', 'three')
// [Arguments, ['one', 'two', 'three']]

But obviously that doesn't work.

Share Improve this question asked Jan 14, 2016 at 18:39 brandonscriptbrandonscript 73.1k35 gold badges174 silver badges237 bronze badges 2
  • Not sure about your exact use case but maybe the option object pattern is a better choice, e.g.: function foo(o) { log(o.name) } foo({ name: "Bar" }) – lleaff Commented Jan 14, 2016 at 18:44
  • @lleaff this needs to be more flexible than that unfortunately
发布评论

评论列表(0)

  1. 暂无评论