【问题标题】:Can I `fn.apply` with `arguments` or do I've to convert `arguments` to Array first?我可以使用 `arguments` `fn.apply` 还是必须先将 `arguments` 转换为 Array?
【发布时间】:2016-01-27 16:35:06
【问题描述】:

我正在学习 .applyarguments,我有一个问题 - 我可以 fn.applyarguments 还是我必须先将 arguments 转换为 Array?

我创建的这个代码示例表明我可以只使用applyarguments

function aaa () {
    bbb.apply(undefined, arguments)
}

function bbb () {
    console.dir(arguments)
}

aaa(1,2,3,4) // calls bbb and bbb's arguments are 1, 2, 3, 4

我也可以将参数转换为数组,它也可以:

function aaa () {
    var args = Array.prototype.slice.call(arguments);
    bbb.apply(undefined, args)
}

function bbb () {
    console.dir(arguments)
}

aaa(1,2,3,4) // calls bbb and bbb's arguments are 1, 2, 3, 4

我应该使用一个还是另一个,有什么区别吗?

【问题讨论】:

  • 不需要转成数组,可以直接使用arguments

标签: javascript arrays arguments


【解决方案1】:

您不必将arguments 转换为数组。 Any array-like argument will do:

var args = {0: 1, 1: 2, 2: 3, length: 3}
// Note that this is an object, not an array

function test() { console.log(arguments); }

test.apply(undefined, args);
// Logs [1, 2, 3]

但是,有理由直接传递arguments,而不是将其转换为数组,然后再传递给apply。例如,直接传递arguments 在某些浏览器中进行了优化(例如,that it is optimized in Chrome)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-18
    • 1970-01-01
    • 2013-08-26
    • 1970-01-01
    • 2016-01-27
    • 2018-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多