对参数和其他对象进行切片

时间:2017-10-18 20:57:19

标签: javascript arrays node.js

我知道这是一种反模式:

var args = Array.prototype.slice.call(arguments, 0);

但是我的问题只是这行代码。我不确定它为什么会起作用。当我打印出arguments对象时,例如

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

test(1,2)
//Outputs: { '0': 1, '1': 2 } 

如果我切片参数对象

function test(){
    console.log(Array.prototype.slice.call(arguments));
}
test (1,2)
//Outputs: [1,2]

我会在数组中获取参数。 即使我向参数对象附加了某些内容,切片仍会在数组中生成参数:

function test(){
    arguments['2'] = 3;
    console.log(arguments)
    console.log(Array.prototype.slice.call(arguments));
}

test (1,2)
//Outputs: { '0': 1, '1': 2, '2': 3 }
//[ 1, 2 ]

如果它将对象作为对象放入slice.call

Array.prototype.slice.call({'0':1, '1':2}, 0)

我会得到一个空数组。 知道为什么切片适用于参数对象吗?

2 个答案:

答案 0 :(得分:2)

因为它是具有length属性的array like object。如果您使用数字键将length添加到对象(忽略非数字键),则生成的数组将包含值。



console.log([].slice.call({'0':1, '1':3, a: '5', length: 2}, 0));




注意:

  1. [].sliceArray.prototype.slice的简写。

  2. Slicing arguments数组广泛用于ES5。不幸的是,它会导致内存泄漏(请参阅optimisation killers)。

  3. 在ES6中,您可以使用rest parameter function x(...args),而args将是一个数组。

答案 1 :(得分:0)

arguments是一个具有length属性的特殊对象

arguments = {'0':1, '1':2, length: 2}

如果您已将length属性添加到对象,则切片将起作用

尝试使用typeof arguments [length]来查看参数的长度属性