出于我无法理解的原因,诀窍是将外循环向下循环(i--),将内循环向上循环(j++)。
请参见下面的示例:
function test() {
var array1 = new Array("a","b","c","d","e","f");
var array2 = new Array("c","e");
for (var i = array1.length - 1; i >= 0; i--) {
for (var j = 0; j < array2.length; j++) {
if (array1[i] === array2[j]) {
array1.splice(i, 1);
}
}
}
console.log(array1)
}
我怎么知道这个?见下文:
for( var i =myArray.length - 1; i>=0; i--){
for( var j=0; j<toRemove.length; j++){
if(myArray[i] === toRemove[j]){
myArray.splice(i, 1);
}
}
}
或者
var myArray = [
{name: 'deepak', place: 'bangalore'},
{name: 'chirag', place: 'bangalore'},
{name: 'alok', place: 'berhampur'},
{name: 'chandan', place: 'mumbai'}
];
var toRemove = [
{name: 'deepak', place: 'bangalore'},
{name: 'alok', place: 'berhampur'}
];
for( var i=myArray.length - 1; i>=0; i--){
for( var j=0; j<toRemove.length; j++){
if(myArray[i] && (myArray[i].name === toRemove[j].name)){
myArray.splice(i, 1);
}
}
}
alert(JSON.stringify(myArray));
在那张纸条上,谁能解释为什么外循环需要向下循环(--)?
祝你好运!