Javascript 如何删除数组的元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4374676/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to remove elements of array?
提问by user495688
Is it possible to remove the contents of the array based on the index? If I have 2 arrays like these:
是否可以根据索引删除数组的内容?如果我有 2 个这样的数组:
Array1 that contains 15 values and I want to get the last 10 values.
Array1 包含 15 个值,我想获取最后 10 个值。
Before removing elements:
删除元素之前:
array1 == [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14]
After removing elements:
删除元素后:
array1 == [5,6,7,8,9,10,11,12,13,14]
Array2 that contains 15 values and then I want to get only the first 10 values.
Array2 包含 15 个值,然后我只想获取前 10 个值。
Before removing elements:
删除元素之前:
array2 == [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14]
After removing elements:
删除元素后:
array2 == [0,1,2,3,4,5,6,7,8,9]
But there are conditions that must be fulfilled:
但是有一些条件必须满足:
if the array only contains 3 elements is not necessary to discard the elements in the array, as well as if the array contains 10 elements only. but if the array contains more than 10 elements, the excess is discarded.
如果数组只包含 3 个元素,则不需要丢弃数组中的元素,以及如果数组只包含 10 个元素。但如果数组包含 10 个以上的元素,多余的将被丢弃。
回答by Guffa
To keep the first ten items:
要保留前十项:
if (theArray.length > 10) theArray = theArray.slice(0, 10);
or, perhaps less intuitive:
或者,也许不太直观:
if (theArray.length > 10) theArray.length = 10;
To keep the last ten items:
要保留最后十项:
if (theArray.length > 10) theArray = theArray.slice(theArray.length - 10, 10);
You can use a negative value for the first parameter to specify length - n, and omitting the second parameter gets all items to the end, so the same can also be written as:
可以对第一个参数使用负值来指定长度-n,省略第二个参数会得到所有项目到最后,所以同样也可以写成:
if (theArray.length > 10) theArray = theArray.slice(-10);
The splice
method is used to remove items and replace with other items, but if you specify no new items it can be used to only remove items. To keep the first ten items:
该splice
方法用于删除项目并替换为其他项目,但如果您未指定新项目,则只能用于删除项目。要保留前十项:
if (theArray.length > 10) theArray.splice(10, theArray.length - 10);
To keep the last ten items:
要保留最后十项:
if (theArray.length > 10) theArray.splice(0, theArray.length - 10);
回答by Aaron Digulla
Use the function array.splice(index, count)
to remove count
elements at index
. To remove elements from the end, use array1.splice(array1.length - 10, 1);
使用该函数array.splice(index, count)
删除 处的count
元素index
。要从末尾删除元素,请使用array1.splice(array1.length - 10, 1);
回答by Alfred
回答by strager
Kind of hard to follow your question, but try these:
有点难以理解你的问题,但试试这些:
array = array.slice(-10);
// or
last10 = array.splice(-10);
// array has first array.length-10 elements