如何改变"论点"?

mpe*_*pen 30 javascript arrays

这是脚本:

function runScripts() {
    if (arguments.length === 0) return;
    chrome.tabs.executeScript(null, {
        file: arguments[0]
    }, function() {
        arguments.shift();
        runScripts.apply(null, arguments);
    });
}
Run Code Online (Sandbox Code Playgroud)

它不起作用,因为arguments它实际上不是一个数组,它只是数组.那么我怎样才能"移动"它或者破解第一个元素以便我可以递归地应用这个函数呢?

Clo*_*boy 35

var params = Array.prototype.slice.call(arguments);
params.shift();
Run Code Online (Sandbox Code Playgroud)

您可以查看此博文,更详细地解释它.

  • 这里有一个小的优化,可以保护您免受修改的“Array”的影响:“[].slice.call(arguments)”。 (2认同)

use*_*716 23

我假设您想要引用原始内容 arguments,而不是您要传递给的回调中的内容chrome.tabs.executeScript.

如果是这样,您需要先缓存它.

function runScripts() {
    if (arguments.length === 0) return;
    var args = [];
    Array.prototype.push.apply( args, arguments );

    chrome.tabs.executeScript(null, {
        file: args.shift();
    }, function() {
             // using the modified Array based on the original arguments object
        runScripts.apply(null, args);
    });
}
Run Code Online (Sandbox Code Playgroud)


the*_*lum 11

[].shift.call(arguments)也有效.我在生产代码中使用它,它按预期工作.

使用这种方法,您的功能变得更加简洁:

function executeScripts() {
    if (arguments.length === 0) return;
    chrome.tabs.executeScript(null, {
        file: [].shift.call(arguments)
    }, function() {
        executeScripts.apply(null, arguments);
    });
}
Run Code Online (Sandbox Code Playgroud)

如果您查看MDN,他们会说明shift()在实现这种灵活性的情况下.

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/shift


Dav*_*ard 6

您可以转换arguments为常规数组,如下所示:

var args = Array.prototype.slice.call(arguments);
Run Code Online (Sandbox Code Playgroud)


小智 5

只想指出[] .shift.call(arguments)的潜在问题.

这似乎有可能不明确的意图转移你的参数 - 即使你的函数的命名参数 - 即使在shift语句之前使用.

例如,

function testShift (param1, param2) {
    [].shift.call(arguments); 
    if (param1=="ONE") alert("ONE");
}
Run Code Online (Sandbox Code Playgroud)

如果您拨打以下电话,您可能会发生什么?

testShift("ONE", "TWO");
Run Code Online (Sandbox Code Playgroud)

如果您希望param1保持"ONE",那么您的修复是在转换发生之前将var设置为param1.看起来javascript没有绑定param1,直到它被调用的行 - 而不是在调用函数时...所以在使用参数之前对参数的修改会产生意想不到的效果.

希望现在,你能够期待它.