In Array section, we learnt different ways of manipulating array elements. In this post, we shall learn how to empty an array in different ways and will also understand which method is the best way to emptying an array in JavaScript.
In below code snippet, we have a function which has an array declared named a
.
function ClearArray()
{
var a = ["India", "Pakisthan", "Bangladesh", "China"];
alert("Original array: " + a);
a = ["India", "Pakisthan", "Bangladesh", "China"];
a.length = 0;
alert("1st output: " + a);
// 2nd way
a = ["India", "Pakisthan", "Bangladesh", "China"];
a = [];
alert("2nd output: " + a);
// 3rd way
a = ["India", "Pakisthan", "Bangladesh", "China"];
a.splice(0, a.length);
alert("3rd output: " + a);
// 4th way
a = ["India", "Pakisthan", "Bangladesh", "China"];
while(a.length)
{
a.pop();
}
alert("4th output: " + a);
}
We are doing following in the above code snippet
After testing we have come to the conclusion that 2nd and 3rd way is better than any others.
Views: 6087 | Post Order: 159