its*_*sme 125 javascript arrays
我的情况:
var id_tag = [1,2,3,78,5,6,7,8,47,34,90];
Run Code Online (Sandbox Code Playgroud)
我想delete where id_tag = 90
和回来:
var id_tag = [1,2,3,78,5,6,7,8,47,34];
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
Jos*_*ber 216
你会想要使用JavaScript的Array splice
方法:
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);
Run Code Online (Sandbox Code Playgroud)
PS有关那个很酷的~
波浪形快捷方式的解释,请看这篇文章:
注意: 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);
Run Code Online (Sandbox Code Playgroud)
如果你想支持IE <9,但还没有jQuery的页面上,没有必要使用它只是为$.inArray
.您可以改用此polyfill.
Pet*_*ete 17
如果您要经常使用它(并且在多个数组上),请扩展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)
Run Code Online (Sandbox Code Playgroud)
Eli*_*rey 11
tag_story.splice(tag_story.indexOf(id_tag), 1);
Run Code Online (Sandbox Code Playgroud)
我喜欢使用过滤器:
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;
}
});
Run Code Online (Sandbox Code Playgroud)