2

我有一个数组。我想删除任何超过第三个项目的项目,在数组中留下“a”、“b”和“c”。我该怎么做呢?

//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'];
4

2 回答 2

4

你可以简单地做:

array_name.splice(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"]
于 2013-06-04T16:01:56.847 回答
3

.length只需将其设置为较小的数字即可截断数组。

array_name.length = 3;

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

于 2013-06-04T16:12:07.430 回答