移除大于的数组项.号码

Remove array items larger than .. number

本文关键字:号码 数组 大于      更新时间:2023-09-26

我有一个数组。我想删除任何超过第三项的项,在数组中留下'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'];

你可以这样做:

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"]

通过简单地将其.length设置为较低的数字来截断数组。

array_name.length = 3;

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