在 JavaScript 中按值从数组中删除项目会产生不可预测的结果
我有这段代码,用于通过 JS 中的值从数组中删除项目...
function remove_item(index){
//log out selected array
console.log('before >> ' + selected); //
//log out item that has been requested to be removed
console.log('removing >> ' + index);
//remove item from array
selected.splice( $.inArray(index,selected) ,1 );
//log out selected array (should be without the item that was removed
console.log('after >> ' + selected);
//reload graph
initialize();
}
这就是我的数组的样子...
selected = [9, 3, 6]
如果我调用 remove_item(3)
这就是被注销的内容..之后
before >> 9,3,6
removing >> 3
after >> 9,3
应该是 9,6
而不是 9,3
我完全被这个问题难住了,因为它有时有效,有时无效......
例如我刚刚尝试过 < code>remove_item(10) 这有效...
before >> 1,2,10
removing >> 10
after >> 1,2
我确保它与此行有关:
selected.splice( $.inArray(index,selected) ,1 );
非常感谢任何帮助。
I have this code for removing an item from an array by value in JS...
function remove_item(index){
//log out selected array
console.log('before >> ' + selected); //
//log out item that has been requested to be removed
console.log('removing >> ' + index);
//remove item from array
selected.splice( $.inArray(index,selected) ,1 );
//log out selected array (should be without the item that was removed
console.log('after >> ' + selected);
//reload graph
initialize();
}
This is what my array looks like...
selected = [9, 3, 6]
If I call remove_item(3)
this is what gets logged out...
before >> 9,3,6
removing >> 3
after >> 9,3
After should be 9,6
not 9,3
I'm totally stumped on this as it sometimes works and sometimes doesn't...
For example I just tried remove_item(10)
and this worked...
before >> 1,2,10
removing >> 10
after >> 1,2
I'm sure it has something to do with this line:
selected.splice( $.inArray(index,selected) ,1 );
Any help much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果不一致的话,有时参数
index
是字符串,有时是数字。$.inArray('3', arr)
将返回-1
。$.inArray(3, arr)
将返回1
。请参阅 splice 文档。
您可以通过执行以下操作来确保它始终是一个数字:
...或...
If it's inconsistent, sometimes the parameter
index
is a string, and sometimes it's a number.$.inArray('3', arr)
will return-1
.$.inArray(3, arr)
will return1
.See splice's docs.
You can make sure it's always a number by doing this:
... or ...
我测试了你的代码,它按预期工作。
我认为您需要再次检查您的输入数组。
真的是[9,3,6]还是你期望它是那样?
I tested your code and it works as intended.
I think you need to check your input array once more.
Is it really [9,3,6] or do you expect it to be that?