2017-05-26 113 views
0

Mozilla Developer Network這是原始鏈接。如何理解一個關於Array.prototype.copyWithin()的例子?

我在學習MDN的Array.prototype。現在,我對Array.prototype.copyWithin()的一個例子感到困惑。請幫助我,謝謝你的幫助。

例如,下面的代碼可能被我忽略,運行的答案等於我的答案。我認爲第一個代碼像第二個代碼一樣被低估。所以,我知道答案。

console.log([].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4)); // TypedArray => [4, 2, 3, 4, 5] 
console.log(new Int32Array([1, 2, 3, 4, 5]).copyWithin(0,3,4)); // TypedArray => [4, 2, 3, 4, 5] 

但是,下一個代碼,我無法理解。

console.log([].copyWithin.call({length: 5, 3: 1}, 0, 3)); // How to execute?

這些實例是從Mozilla的開發人員網絡。

回答

0

Array#copyWithin方法可以調用與任何對象Function#call,只要它有一個length屬性和數字鍵。 MDN上的代碼將Array#copyWithin稱爲對象{ length: 5, 3: 1 },因爲它的值爲this或實例值。這是該方法運行的「陣列」。

一個數組只是一個對象,一個具有length和數字,有序屬性的特殊對象。同樣的事情發生在這裏。他們通過傳遞一個具有length和數字鍵的對象來「嘲笑」一個數組,而不是一個數組。

同樣的操作情況,因爲這兩個數組和{ length: 5, 3: 1 }

  • length財產
  • 有數字鍵
+0

我明白了。當代碼像'[] .copyWithin.call(Object,arguments)'時,copyWithin()的參數是Object的關鍵。參數不是數組,而是參數是數組的索引。我之前對Array的理解很狹窄,非常感謝。 – Huooo