简体   繁体   English

删除大于..数字的数组项

[英]Remove array items larger than .. number

I have an array. 我有一个阵列。 I would like to remove any items that surpass the third item leaving 'a', 'b', and 'c' in the array. 我想删除任何超过第三项的项目,在数组中留下'a','b'和'c'。 How do I do this? 我该怎么做呢?

//my array
var array_name = ['a', 'b', 'c', 'd', 'e'];

//Number of array items to remove
var remove_array_items = 3;

//Desired result
var array_name = ['a', 'b', 'c'];

You can simply do: 你可以简单地做:

array_name.splice(remove_array_items);

to remove all elements on or after the one at index: remove_array_items 删除索引处或之后的所有元素: remove_array_items


var array_name = ['a', 'b', 'c', 'd', 'e'];
var remove_array_items = 3;

// note this **modifies** the array it is called on
array_name.splice(remove_array_items);

// array_name is now ["a", "b", "c"]

Truncate the Array by simply setting its .length to a lower number. 只需将.length设置为较小的数字即可截断Array。

array_name.length = 3;

DEMO: http://jsfiddle.net/hX29y/ 演示: http : //jsfiddle.net/hX29y/

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

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