代码片段 → jQuery 代码片段 → 从数组中删除特定值 从数组中删除特定值 Chris Coyier 于 2012 年 1 月 29 日 var arr = [1, 2, 3, 4, 5]; var removeItem = 2; arr = $.grep(arr, function(value) { return value != removeItem; });
第一行缺少分号,除此之外,都很棒
为什么不使用原生函数呢?
var arr = [1, 2, 3, 4, 5];
var removeItem = 2;
arr.splice(arr.indexOf(removeItem ), 1);
非常感谢!
请您添加一个 js.fiddle 链接的实时示例吗?
给你
http://codepen.io/chriscoyier/pen/65/3
存在 Splice() 方法,该方法从数组中的索引处删除项目。
代码
var arr = [1, 2, 3, 4, 5];
var removindexitem = 2;
arr.splice(removindexitem );
参考
https://w3schools.org.cn/jsref/jsref_splice.asp
你需要知道该值在数组中的索引才能使其生效。这并不总是保证的,而且原生 indexOf 在 IE9 以下版本的 IE 中也不起作用。
array.pull(value); // 删除
array.push(value); // 添加
抱歉…
array.pop(value) // 删除
@oottoo
array.pop(value) 仅从数组中删除最后一个值。
pop 功能仅用于最后一个元素。