2017-10-18 42 views
0

我明白這是一個反模式做:片上的參數和其他對象

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

但是我的問題是,只是這行代碼。我不確定它爲什麼有效。當我打印出來的參數對象,例如

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

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

如果我切片arguments對象

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

我會得到的參數在數組中。 即使我追加的東西arguments對象切片仍然得到參數數組中的:

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) 

我會得到一個空陣列。 任何想法爲什麼切片在參數對象上工作?

+0

https://github.com/v8/v8/blob/master/src/js/array.js < - 我相信這是該方法實施的地方。 – djfdev

回答

1

因爲這是array like objectlength屬性。如果您將length添加到具有數字鍵的對象(非數字鍵被忽略),則結果數組將包含這些值。

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

注:

  1. [].sliceArray.prototype.slice的簡寫。

  2. Slicing arguments數組在ES5中被廣泛使用,它不是反模式。

  3. 在ES6中,您可以使用rest parameterfunction x(...args)並且args將是一個數組。

+0

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments它確實說它會減慢程序並停止優化,如果您對參數執行切片? –

+0

如果您覺得切片是慢的原因,請務必將其更換。但是,不要做過早的優化。另外,現在你可以使用'... args'。 –

0

論點是有length屬性

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

,如果你有length屬性添加到您的對象的特殊對象,切片將工作

嘗試做的typeof參數[長度]看參數的長度屬性

相關問題