deleting a specific object in a javascript array
im doing a test on deleting objects inside an array... since this is a test, this is rather an informal code..
<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>
now this code works fine (deleting an object on the array) but it deletes the one after the one i want deleted (in the code above, i want to delete the object in index 2, but it deletes the object in index 3)
anything i'm doing wrong in this code?
TIA :)
You should never try to alter an array while iterating it. Instead, save the index of the element you want to delete in a variable, and remove it after the for loop.
This should work:
<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>
Use ''filter'' as implemented in underscore.js:
_.filter(fruits, function (fruit) {
return fruit.test1 !== "test2";
});
This has the advantage of using a fast, native JavaScript method (''filter'') where available.
精彩评论