0

我有这段代码用于在 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 );

非常感谢任何帮助。

4

2 回答 2

3

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

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

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

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

请参阅splice 的文档

您可以通过这样做确保它始终是一个数字:

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

... 或者 ...

function remove_item(index){
  index = Number(index);
于 2011-05-22T12:51:45.450 回答
0

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

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

于 2011-05-22T12:25:06.750 回答