2011-09-02 79 views
1

即时通讯做上删除阵列......因为这是一个测试,这是相当非正式的代码中的对象测试..在JavaScript数组删除特定对象

<script type="text/javascript"> 

// initialize array and objects 
var fruits = new Array(); 

var z = { 
    test1: "test0", 
    test2: "test2" 
} 

fruits.push(z); 
var z2 = { 
    test1: "test1", 
    test2: "test2" 
} 
fruits.push(z2); 
var z3 = { 
    test1: "test2", 
    test2: "test2" 
} 
fruits.push(z3); 
var z4 = { 
    test1: "test3", 
    test2: "test2" 
} 
fruits.push(z4); 
var z5 = { 
    test1: "test4", 
    test2: "test2" 
} 
fruits.push(z5); 

// display array length 
document.write("array length is " + fruits.length + "<br>"); 

// traverse array 
for(var x = 0; x < fruits.length; x++){ 

    // display object content in array 
    document.write(fruits[x].test1 + " "); 

    // delete object in array where variable test1 is equal to "test2" 
    if(fruits[x].test1 == "test2"){ 
    fruits.splice(x, 1); 
    //document.write("array length is " + fruits.length + "<br>"); 
    } 
} 
</script> 

现在这个代码工作正常(删除数组上的一个对象),但它删除一个我想要删除的一个(在上面的代码中,我想删除索引2中的对象,但它删除索引3中的对象)

任何我在这段代码中做错了吗?

TIA :)

回答

0

这应该工作:

<script type="text/javascript"> 

    // initialize array and objects 
    var fruits = new Array(); 

    var z = { 
     test1: "test0", 
     test2: "test2" 
    } 

    fruits.push(z); 
    var z2 = { 
     test1: "test1", 
     test2: "test2" 
    } 
    fruits.push(z2); 
    var z3 = { 
     test1: "test2", 
     test2: "test2" 
    } 
    fruits.push(z3); 
    var z4 = { 
     test1: "test3", 
     test2: "test2" 
    } 
    fruits.push(z4); 
    var z5 = { 
     test1: "test4", 
     test2: "test2" 
    } 
    fruits.push(z5); 

    // display array length 
    document.write("array length is " + fruits.length + "<br>"); 

    // traverse array 
    for(var x = 0; x < fruits.length; x++){ 

     // display object content in array 
     document.write(fruits[x].test1 + " "); 

     // delete object in array where variable test1 is equal to "test2" 
     if(fruits[x].test1 == "test2"){ 
     fruits.splice(x-1, 1); 
     //document.write("array length is " + fruits.length + "<br>"); 
     } 
    } 
    </script> 
+0

感谢您的回答迈克:)不幸的是,我曾尝试过这种解决方法,但它仍然没有完成这项工作......你有其他的想法吗?再次感谢:) – jason

6

你不应该尝试在迭代它改变一个数组。相反,将要删除的元素的索引保存在变量中,并在for循环之后将其删除。

+0

做到了这一点:D非常感谢你:) – jason

0

使用在underscore.js '' 过滤器 '' 为implemented

_.filter(fruits, function (fruit) { 
    return fruit.test1 !== "test2"; 
}); 

这具有使用快速的,原生的JavaScript方法( '' 过滤器 ''),其中可用的优势。

+0

感谢您的回应阿德里安,我也会尝试这个解决方法:) – jason

相关问题