处理Array.prototype.slice.call(参数)的更清洁的方法 [英] Cleaner way of handling Array.prototype.slice.call(arguments)

查看:73
本文介绍了处理Array.prototype.slice.call(参数)的更清洁的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写几个带有不同类型参数的函数。因此,这样做要简单得多:

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)虽然增加了很多代码,但也降低了可读性。我试图找出是否有办法编写一个辅助函数,可以完成与 Array.prototype.slice.call()相同的操作,但更清洁,更简单阅读。我尝试的是:

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 accomplish 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']]

但显然这不起作用。

推荐答案

你需要传递 foo 的arguments对象,只切片,就像这样

You need to pass the arguments object of foo and slice only that, like this

function parseArgs(args) {
    return Array.prototype.slice.call(args);
}

使用参数时 parseArgs 里面,它将引用该函数收到的参数,而不是 foo 收到的参数。

When you use arguments inside parseArgs it will refer to the arguments received by that function only not the one which foo received.

在ECMA Script 2015中,您可以使用 Array.from arguments 直接对象,像这样

In ECMA Script 2015, you can use Array.from on arguments object directly, like this

function foo() {
    console.log(Array.from(arguments));
}






或者,您可以保留 parseArgs 原样并将参数分散到 parseArgs 在ECMA Script 2015中,像这样


Alternatively, you can keep the parseArgs as it is and spread the arguments over parseArgs in ECMA Script 2015, like this

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

function foo() {
    console.log(parseArgs(...arguments));
}

这基本上意味着您正在传播参数 foo 收到并将它们传递给 parseArgs ,以便它也会收到相同的参数。

This basically means that you are spreading the arguments received by foo and passing them over to parseArgs so that it will also receive the same arguments.

这篇关于处理Array.prototype.slice.call(参数)的更清洁的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆