Currently, I am conducting an experiment on removing objects from an array. Please note that this code is not formal as it is intended for testing purposes.
<script type="text/javascript">
// Initialize array and objects
var fruits = new Array();
var obj1 = {
test1: "test0",
test2: "test2"
}
fruits.push(obj1);
var obj2 = {
test1: "test1",
test2: "test2"
}
fruits.push(obj2);
var obj3 = {
test1: "test2",
test2: "test2"
}
fruits.push(obj3);
var obj4 = {
test1: "test3",
test2: "test2"
}
fruits.push(obj4);
var obj5 = {
test1: "test4",
test2: "test2"
}
fruits.push(obj5);
// Display array length
document.write("The array's length is " + fruits.length + "<br>");
// Traverse the array
for(var i = 0; i < fruits.length; i++){
// Display object content within the array
document.write(fruits[i].test1 + " ");
// Delete object in the array if variable test1 is equal to "test2"
if(fruits[i].test1 == "test2"){
fruits.splice(i, 1);
//document.write("array length is " + fruits.length + "<br>");
}
}
</script>
The code above currently works for removing an object from the array. However, it deletes the object following the one intended for deletion (for example, wanting to remove index 2 results in index 3 being deleted).
Is there anything flawed with the current implementation?
Thanks in advance :)