【问题标题】:How JS 'arguments' object gets converted to arrayJS 'arguments' 对象如何转换为数组
【发布时间】:2016-01-27 16:39:16
【问题描述】:

寻找有关执行以下操作时究竟发生了什么的更多详细信息:

    function useArray(){
        var args = [].slice.call(arguments)
        console.log(args)
    }

为什么slice 是一个具有 3 个参数(源数组、要复制的开始和结束位置)威胁arguments 的函数?方法 call 需要第一个参数的正确值,因为 this 但似乎 arguments 变成了 Array 对象?

以及为什么这不起作用:

var args = [].slice(arguments)

【问题讨论】:

    标签: javascript arrays function arguments


    【解决方案1】:

    我们使用[].slice 来获取Array::slice 方法。 arguments 没有自己的 slice(),但它类似于数组。

    虽然它是Array 的成员,但slice() 在类似数组的对象(具有.length 并且可以用[0..n] 索引的对象)上也能很好地工作。

    slice() 不带参数返回整个数组的副本。它的参数都是可选的。

    所以就好像arguments 一个slice() 方法,我们调用arguments.slice() 来获取它的一个副本(作为一个数组)。

    [].slice(arguments) 只是在一个空数组上调用Array::slice()arguments 作为begin 参数,这是没有意义的,因为begin(如果存在)应该是一个数字。

    【讨论】:

    • 非常感谢您的详细解释。现在很清楚为什么[].slice(arguments) 返回空数组。还有一件事要仔细检查。我说得对吗,说[].slice.call(arguments) 传递对象arguments 作为调用的接收者,函数对象的call() 方法应该作为第一个参数?
    • 如果我没看错的话,是的。就好像slice 暂时是arguments 的成员——argumentsslice 调用中将是this
    猜你喜欢
    • 2012-05-07
    • 2022-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 2020-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多