2017-05-30 53 views
1

當我使用Array.prototype.copyWithin方法:的JavaScript Array.copyWithin方法

[1, 2, 3, 4, 5].copyWithin(-3,0,-1); 

輸出是

[1, 2, 1, 2, 3] 

如何是數字1,2,3添加到輸出結果?

+0

你有什麼期待輸出? –

+0

我期待[1,2,1,4,5] –

+0

@GuruDeepak問題是,你爲什麼期望這是答案。 – ScrapCode

回答

3

你有

[1, 2, 3, 4, 5].copyWithin(-3, 0, -1); // [1, 2, 1, 2, 3] 

什麼你做什麼

[1, 2, 3, 4, 5]   values 
0 1 2 3 4   indices from start 
-5 -4 -3 -2 -1   indices from end 
^ ^ ^  needed indices 
|  |  +-------- end 
|  +-------------- target  
+-------------------- start 
[1, 2, 3, 4, 5]  given array 
[  1, 2, 3, 4, 5] copied values 
[1, 2, 1, 2, 3]  result array, keeping the same length 

您需要改變開始和結束值。

基本上你有4個可能性,無論是從開始或結束獲得指數。

[1, 2, 3, 4, 5] values 
0 1 2 3 4 indices from start 
-5 -4 -3 -2 -1 indices from end 
^^^   needed indices 
| | +------- target  
| +---------- end 
+------------- start 

console.log([1, 2, 3, 4, 5].copyWithin(2, 0, 1).join(', ')); 
 
console.log([1, 2, 3, 4, 5].copyWithin(2, -5, -4).join(', ')); 
 
console.log([1, 2, 3, 4, 5].copyWithin(-3, 0, 1).join(', ')); 
 
console.log([1, 2, 3, 4, 5].copyWithin(-3, -5, -4).join(', '));

+0

在這[1,2,3,4,5] .copyWithin(-3,0,-1);目標是-3並且開始是0並且結束是-1禮?所以輸出應該是[1,2,1,4,5]儀式? –

+0

是正確的,但是如果數組小於所需數量的項目,誰在開始和結束之間,結束並不重要。 –

+0

實際上我很困惑 –

0

console.log([1,2,3,4,5].copyWithin(2, 0, 1))

+2

需要說明 –

+0

雖然此代碼可能回答此問題,但提供有關如何解決問題和/或爲何解決問題的其他上下文會提高答案的長期價值。 – Badacadabra

+0

原來,其他人已經做到了。即使我是第一個正確回答的人,我將不得不刪除我的答案。 – arboreal84

0

您的目標是-3([1,2,3 ,4,5]),這是複製的開始位置。 您的開始爲0([,2,3,4,5]),這是您要複製的序列的開始。 Your End is -1([1,2,3,4,]),這就是你的序列結束的地方。

因此,您將1,2,3,4,5從索引2(值3)開始放入您的數組中。

因爲如果你想1,2,1,4,5 copywithin不會改變陣列的你1,2,1,2,3

長度,你將不得不使用[1, 2, 3, 4, 5].copyWithin(-3,0,-4);

+0

**所以你是從索引2(值3)開始將1,2,3,4,5放到你的數組中。**我沒有得到這部分 –

+0

你誤解了目標,它是放置副本的地方。第二個參數是從哪裏開始的,因此副本放置在2之後並且由1到4(包括1和4)組成。但是由於長度沒有改變,副本在第5個索引處被截斷。 – RobG

0

要獲得[1,2,1,4,5]做 [1, 2, 3, 4, 5].copyWithin(2,0,1)

console.log([1, 2, 3, 4, 5].copyWithin(2,0,1));

copyWithin

array.copyWithin(目標,開始,結束)

目標的說明:必需。索引位置的元素複製到,

開始:索引位置開始從,

複製元素:可選。索引位置到停止複製元件從(默認爲array.length)

在你的情況變化應該從第三位置開始(即索引= 2),所以目標= 2,並開始從第一位置複製,所以start = 0,只有一個元素需要複製。因此最終在指數= 1,這意味着末= 1

看看here

+0

我在2分鐘前回答了同樣的問題。 – arboreal84

+0

@ arboreal84你想我刪除我的答案? –

+0

只是考慮OP。 – arboreal84