在JavaScript中按值从数组中删除项目会产生不可预测的结果

时间:2011-05-22 12:11:32

标签: javascript arrays splice

我有这个代码用于通过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

应该{​​{1}}而不是9,6

我对此很感兴趣,因为它有时会起作用,有时却不会......

例如,我刚试过9,3这就有效了......

remove_item(10)

我确信它与这一行有关:

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

任何帮助都非常感激。

2 个答案:

答案 0 :(得分:3)

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

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

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

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

请参阅splice's docs

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

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

......或......

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

答案 1 :(得分:0)

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

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