2

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

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

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

DeletedConditions字符串可以是任何东西。

请帮帮我。如何完成这项工作。

4

6 回答 6

1

首先,我建议你正式把索引变成一个正式的数组。将字符串作为索引引用,如果存在值没有被分隔的情况,您很容易错过拆分,

然后代码

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"] 

​</p>

于 2012-11-06T05:37:45.440 回答
1

在循环内拼接后,您始终可以递减 k 迭代器:

k--;
于 2012-11-06T05:25:27.710 回答
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(', '))
于 2012-11-06T05:27:36.137 回答
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;});

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

于 2012-11-06T05:38:24.690 回答
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);
于 2012-11-06T05:42:20.867 回答
-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);
}
于 2012-11-06T05:37:24.773 回答