2017-12-27 930 views
-1

每一個在我的列表中的元素的一個數組持有的意見,如Javascript - 如何將特定索引中的元素插入到數組的末尾?

for (let i = 0; i < myList; i ++) { 
    myList[i][‘comments’] = []; 
} 

我的失敗嘗試:

if (someCondition) { 
    // insert from index k to the end of the array 
    myList[‘comments’].splice(k, 0, 「newElement」); 
} 

一個例子:

myList = [ 「comments」: [「1, 2」], 「comments」:[], 「comment」: [「2」, 「2」], 「comment」: [] ] 

目標: 插入來自索引2

myList = [ 「comments」: [「1, 2」], 「comments」:[], 「comment」: [「2」, 「2」, 「newElement"], 「comment」: [「newElement」] ] 
+1

只是爲了澄清,「插入」是指您移動元素還是複製元素?所以如果你有一個數組'a = [「a」,「b」,「c」,「d」]'那麼將會從索引1插入'[「a」,「c」,「d 「,」b「]或'[」a「,」b「,」c「,」d「,」b「]'? – JJJ

+0

我想OP希望'myList ['comments']。push(myList ['comments']。splice(k,1)[0])' – mhodges

+0

@JJJ新增上面的例子 –

回答

0

array.push(「string」);會將元素推到數組的末尾。

array.splice(k,1);將從數組中刪除具有key = k的項目。

你可以這樣做:

array.push(array[k]); 
array.splice(k,1); 
+1

或者:'array.push(... array.splice(k,1));'或'array.push(array.splice(k,1)[0]) ;' – mhodges

0

將元素添加到您的陣列可以使用蔓延運營商。

let myArray = [ 1, 2, 3, 4]; 
myArray = [ ...myArray, 5 ]; // This will add 5 to your array in the very last 

或者,如果您希望將它添加到數組中的第一個位置,則可以簡單地執行此類操作。

myArray = [ 55, ...myArray]; // Will add 55 as the first index in your array 

要從數組中刪除元素,您可以使用Array.filter方法。具體如下:

myArray = myArray.filter(val => val !== 5); // This will remove 5 element from your array. 
相關問題