使用array.splice()添加和删除特定的数组元素 [英] add and remove specific array elements using array.splice()
问题描述
是否可以添加到数组的特定部分,然后删除数组的特定部分,在这种情况下,使用 arr.splice()
?
我目前这样:
var arr = [ 1,2,3,4,5,6,7,8,9];
arr.splice(0,0, test);
应返回:
测试,1,2,3,4,5,6,7,8,9
i然后执行:
arr.pop();
应返回:
test,1,2,3,4, 5,6,7,8
我想知道是否可以通过 arr.splice()
方法,或者是否有任何更清洁的方法来做相同的事情,因为可能我会做几次,所以最终结果会像这样: / p>
arr.splice(0,0, test);
arr.pop();
arr.splice(1,0, test2);
arr.pop();
看着 array.splice 文档,它建议我只能在将新元素放入的位置删除该元素,没什么不同。
您可以使用 Array.from()
设置 .length
和单个调用中数组的特定索引的值
var arr = [1,2,3,4,5,6,7,8,9]; arr = Array.from({{length:arr.length-1,。 ..arr,0: test}); console.log(arr);
要实现问题中描述的模式,您也可以使用循环和 Object.assign()
var arr = [1,2,3,4,5,6,7,8,9]; var n = 0 ; var prop = test; while(arr.length> 1){Object.assign(arr,{length:arr.length -1,... arr,[n] :! n?prop:prop + n }) ; ++ n; console.log(arr);}
Is it possible to add to a specific part of an array, and then deleting a specific part of the array, in this case the end value using arr.splice()
?
i currently do this like so:
var arr = [1,2,3,4,5,6,7,8,9];
arr.splice(0,0,"test");
which should return:
"test",1,2,3,4,5,6,7,8,9
i then do:
arr.pop();
which should return:
"test",1,2,3,4,5,6,7,8
I was wondering if it's possible to do this via the arr.splice()
method or if there is any cleaner method to do the same, as potentially i'll be doing this a few times, so i would end up with something like:
arr.splice(0,0,"test");
arr.pop();
arr.splice(1,0,"test2");
arr.pop();
looking at the array.splice documentation it suggests i can only delete the element in the position i'm putting the new element into, not a different one.
You can use Array.from()
to set the .length
and values of specific indexes of an array in a single call
var arr = [1,2,3,4,5,6,7,8,9];
arr = Array.from({length:arr.length - 1, ...arr, 0:"test"});
console.log(arr);
To achieve the pattern described at Question you can alternatively use a loop and Object.assign()
var arr = [1,2,3,4,5,6,7,8,9];
var n = 0;
var prop = "test";
while (arr.length > 1) {
Object.assign(arr, {length:arr.length -1,...arr, [n]:!n ? prop : prop+n});
++n;
console.log(arr);
}
这篇关于使用array.splice()添加和删除特定的数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!