在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

我完全被这件事难住了,因为它有时有效,有时不。。。

例如,我刚刚尝试了remove_item(10),结果成功了。。。

before >> 1,2,10
removing >> 10
after >> 1,2

我确信这与这条线有关

selected.splice( $.inArray(index,selected) ,1 );

非常感谢您的帮助。

如果不一致,有时参数index是字符串,有时是数字。

$.inArray('3', arr)将返回-1

$.inArray(3, arr)将返回1

[9, 3, 6].splice(-1, 1);  // removes last item from the array

请参阅拼接的文档。

你可以通过这样做来确保它总是一个数字:

//remove item from array
selected.splice( $.inArray(Number(index),selected) ,1 );

function remove_item(index){
  index = Number(index);

我测试了您的代码,它按预期工作。

我认为您需要再次检查您的输入数组。真的是[9,3,6]吗?还是你认为会是这样?

最新更新