简体   繁体   English

删除从特定位置开始的未知数量的数组元素

[英]Remove Unknown Number of Array Elements Starting at Specific Position

I am aware pop() will remove the last element in a JS array, and that shift() will remove the first one, and that slice() lets you remove elements from an array - and that you can specify what position to start at, and how many to remove, like so: 我知道pop()会删除JS数组中的最后一个元素,而shift()会删除第一个元素,而slice()可以让您从数组中删除元素-并且您可以指定起始位置,以及要删除的数量,例如:

 let cities = ["New York", "Tokyo", "Perth", "Helsinki"]; cities.splice(2, 2); console.log(cities); 

What I'm wondering is if there's a method you can use to start at a certain array position, and remove any additional elements beyond that number? 我想知道的是,是否有一种方法可用于从某个数组位置开始,并删除该数字以外的任何其他元素?

Yeah, splice . 是的, splice Just do not provide the second argument 只是不提供第二个论点

From Docs 文档

deleteCount Optional deleteCount 可选

If deleteCount is omitted, or if its value is larger than array.length - start (that is, if it is greater than the number of elements left in the array, starting at start), then all of the elements from start through the end of the array will be deleted. 如果省略deleteCount,或者其值大于array.length-开始(即,如果大于数组中剩余的元素数量,则从start开始),则所有元素均从start到end阵列中的将会被删除。

 let cities = ["New York", "Tokyo", "Perth", "Helsinki"]; cities.splice(2) console.log(cities) 

只需使用splice提供初始索引,它会假设您需要所有其他值,直到数组结尾

If you don't want to change original array use slice() by passing 0 as first argument 如果您不想更改原始数组,请通过传递0作为第一个参数来使用slice()

 let cities = ["New York", "Tokyo", "Perth", "Helsinki","Landon"]; let number = 1 console.log(cities.slice(0,number)); 

You can do that using splice() if you want to modify original array. 如果要修改原始数组,可以使用splice()进行。

 let cities = ["New York", "Tokyo", "Perth", "Helsinki","Landon"]; let number = 1 cities.splice(number); console.log(cities); 

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

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