从Javascript数组对象中删除记录

时间:2012-11-06 05:24:13

标签: javascript jquery arrays

我有一个java脚本数组对象,我想删除该对象中特定索引的项目,我有一个逗号分隔的索引字符串。问题是当我使用splice删除它时,数组索引被更改,而其他索引的对象没有被删除。

    var DeletedConditions="3, 5, 19, 50";

    for (var k = 0; k < DeletedConditions.split(", ").length; k++) {
         ConditionObject.splice(DeletedConditions.split(", ")[k], 1);
    }

DeletedConditions字符串可以是任何内容。

请帮帮我。如何做到这一点。

6 个答案:

答案 0 :(得分:1)

在循环内部拼接后,您总是可以减少k迭代器:

k--;

答案 1 :(得分:1)

var DeletedConditions="3, 5, 19, 50";
var list = DeletedConditions.split(", ")
for (var k = 0; k < list.length; k++) {
    // using splice here   
    list.splice(k,1); 
     k--;
}

console.log(list.join(', '))

答案 2 :(得分:1)

首先,我建议您正式将索引转换为正式数组。将字符串作为索引引用,如果值不是由,

分隔,则您很容易错过分割

然后the code

var content = ['foo', 'bar', 'baz', 'bam', 'dom', 'zok'],
    deleteIndexes = [5, 1, 3],//should delete zok, bar, bam
    i;

//sort from least to greatest: [1, 3, 5]
deleteIndexes.sort(function(a, b) {
    return a - b;
});

//we loop backwards (performance enhancement)
//now we loop from greatest to least
//we now splice from greatest to least 
//to avoid altering the indexes of the content as we splice
for (i = deleteIndexes.length; i-- > 0;) {
    content.splice(deleteIndexes[i],1);
}

console.log(content); //["foo", "baz", "dom"] 

答案 3 :(得分:1)

如您所观察到的那样,从数组的开头删除项目会将后面的元素向上移动并更改其索引。但是如果你通过项目列表去除向后那么它将首先删除后面的元素,这样对于更接近数组开头的元素,索引仍然是正确的。

此外,不要在每次循环迭代中执行.split()操作 - 效率低下可能对包含四个数字的字符串没有太大影响,但它会产生代码有点乱,原则上它有点令人讨厌。

var DeletedConditions="3, 5, 19, 50",
    delCondArr = DeletedConditions.split();

for (var k = delCondArr.length - 1; k >= 0; k--) {
     ConditionObject.splice(delCondArr[k], 1);
}

如果有可能无法订购DeletedConditions条纹,请在拆分后添加.sort()

delCondArr = DeletedConditions.split().sort(function(a,b){return a-b;});

...在这种情况下,您不需要向后循环。

答案 4 :(得分:1)

复制原始数组可能最简单,省略了过程中删除的项目。像这样的东西会起作用......

var DeletedConditions="3, 5, 19, 50";
DeletedConditions = DeletedConditions.split(', ');
var newConditionObject = [];
for(var k = 0; k < ConditionObject.length; ++k) {
  if(DeletedConditions.indexOf(k) !== -1) { continue; }
  newConditionObject.push(ConditionObject[k]);
}

// result is in `newConditionObject`
console.log(newConditionObject);

答案 5 :(得分:-1)

var fruits = new Array("apple", "banana", "grapes", "oranges","mosambi","aaa","bbb","ccc"); 

var DeletedConditions="1,3,4,5";

var indexArray = new Array;

indexArray = DeletedConditions.split(",");

for (var i = 0; i < indexArray.length; i++) {

   fruits.splice(indexArray[i], 1);
}