Javascript - 如何将特定索引中的元素插入到数组的末尾?
问题描述:
每一个在我的列表中的元素的一个数组持有的意见,如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”] ]
答
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
答
将元素添加到您的阵列可以使用蔓延运营商。
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.
只是为了澄清,“插入”是指您移动元素还是复制元素?所以如果你有一个数组'a = [“a”,“b”,“c”,“d”]'那么将会从索引1插入'[“a”,“c”,“d “,”b“]或'[”a“,”b“,”c“,”d“,”b“]'? – JJJ
我想OP希望'myList ['comments']。push(myList ['comments']。splice(k,1)[0])' – mhodges
@JJJ新增上面的例子 –