简体   繁体   English

使用array.splice()添加和删除特定的数组元素

[英]add and remove specific array elements using array.splice()

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() ? 是否可以添加到数组的特定部分,然后删除数组的特定部分,在这种情况下,使用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()方法执行此操作,或者是否有任何更清洁的方法可以执行此操作,因为我可能会执行几次,所以最终会得到类似以下内容:

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. 查看array.splice文档,它表明我只能删除将新元素放入的位置的元素,而不能删除其他元素。

In answer to my original question as confirmed in the comments. 在评论中确认我对原始问题的回答。 It is not possible to provide a separate index to insert and another to remove in an array using the splice method or potentially any other single statement in javascript. 无法使用splice方法或javascript中可能存在的任何其他单个语句在数组中提供要插入的单独索引和要删除的另一个索引。 The best approach to try to achieve this in a single statement if i really needed it would be to create your own function, which really seems counter productive for the most part. 如果我确实需要,在一个语句中尝试实现此目标的最佳方法是创建自己的函数,这实际上似乎在大多数情况下适得其反。

You can use Array.from() to set the .length and values of specific indexes of an array in a single call 可以使用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); 

To achieve the pattern described at Question you can alternatively use a loop and Object.assign() 要实现Question所描述的模式,您可以选择使用循环和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); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM