我的情况:
var id_tag = [1,2,3,78,5,6,7,8,47,34,90];
我想delete where id_tag = 90并返回:
var id_tag = [1,2,3,78,5,6,7,8,47,34];
我怎样才能做到这一点?
我的情况:
var id_tag = [1,2,3,78,5,6,7,8,47,34,90];
我想delete where id_tag = 90并返回:
var id_tag = [1,2,3,78,5,6,7,8,47,34];
我怎样才能做到这一点?
你会想要使用 JavaScript 的Arraysplice方法:
var tag_story = [1,3,56,6,8,90],
    id_tag = 90,
    position = tag_story.indexOf(id_tag);
if ( ~position ) tag_story.splice(position, 1);
PS有关那个很酷的~波浪号快捷方式的解释,请参阅这篇文章:
使用~波浪号 withindexOf检查数组中是否存在某项。
注意: IE < 9 不支持.indexOf()数组。如果你想确保你的代码在 IE 中工作,你应该使用 jQuery 的$.inArray():
var tag_story = [1,3,56,6,8,90],
    id_tag = 90,
    position = $.inArray(id_tag, tag_story);
if ( ~position ) tag_story.splice(position, 1);
如果您想支持 IE < 9 但页面上还没有 jQuery,则无需仅将其用于$.inArray. 你可以改用这个 polyfill。
如果您要经常使用它(并且在多个数组上),请扩展 Array 对象以创建一个未设置的函数。
Array.prototype.unset = function(value) {
    if(this.indexOf(value) != -1) { // Make sure the value exists
        this.splice(this.indexOf(value), 1);
    }   
}
tag_story.unset(56)
tag_story.splice(tag_story.indexOf(id_tag), 1);
我喜欢使用过滤器:
var id_tag = [1,2,3,78,5,6,7,8,47,34,90];
// delete where id_tag = 90
id_tag = id_tag.filter(function(x) {
    if (x !== 90) {
      return x;
    }
});
作为变种
delete array[array.indexOf(item)];
如果您对delete运算符一无所知,请不要使用此.