问题描述
我有一个数组:
array = ['mario','luigi','kong']
我将其拼接函数称为删除索引前的所有项 :
I call its splice function to remove all items before an index:
array.splice(1) //-> ['luigi','kong']
我只是想知道是否有类似的函数拼接以删除索引后的所有项 :
I'm just wondering if there is a function similar to splice to remove all items after an index:
伪代码
array.mirrorsplice(1) //-> ['mario','luigi']
推荐答案
使用 .length
为数组设置一个新的大小,这比splice()变异更快:
Use .length
to set a new size for an array, which is faster than splice() to mutate:
var array = ['mario','luigi','kong', 1, 3, 6, 8];
array.length=2;
alert(array); // shows "mario,luigi";
为什么它更快?因为 .splice()
必须创建一个包含所有已删除项目的新数组,而 .length
不会创建任何内容,并且返回一个数字而不是一个新数组。
Why is it faster? Because .splice()
has to create a new array containing all the removed items, whereas .length
creates nothing and "returns" a number instead of a new array.
要解决 splice()
的用法,你可以输入一个负指数,以及一个巨大的数字来截断数组的结尾:
To address splice()
usage, you can feed it a negative index, along with a huge number to chop off the end of an array:
var array = ['mario','luigi','kong'];
array.splice(-1, 9e9);
alert(array); // shows "mario,luigi";
这篇关于删除索引后的所有项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!