我有一个数组:

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:

pseudo code

array.mirrorsplice(1) //-> ['mario','luigi']

推荐答案

Use Array.length to set a new size for an array, which is faster than Array.splice to mutate:

var array = ['mario','luigi','kong', 1, 3, 6, 8];
array.length=2;
alert(array); // shows "mario,luigi";

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.

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

Jquery相关问答推荐

在 JSON 对象上使用 jQuery 的 find()

标识符 (id) 是否有通配符 Select 器?

如何在 jQuery Select 器中定义 css :hover 状态?

jQuery 插入 div 作为某个索引

jQuery增量读取AJAX流?

JavaScript 吸管(告诉鼠标光标下像素的 colored颜色 )

jQuery - 用 DIV 跟随光标

如何获取 onclick 调用对象?

blueimp 文件上传插件中的 maxFileSize 和 acceptFileTypes 不起作用.为什么?

专业的基于 jQuery 的 Combobox 控件?

为什么不推荐$().ready(handler)?

隐藏 div 但保留空白

虽然未定义变量 - 等待

订单对象是否由指定的 jQuery Select 器返回?

带有函数的 JavaScript 三元运算符示例

jQuery确定匹配的类是否具有给定的ID

如何在 jQuery 中 Select this中的元素?

在 javascript/浏览器中缓存 jquery ajax 响应

什么时候应该使用 jQuery 的 document.ready 函数?

使用 jQuery/Javascript 防止任何形式的页面刷新