Regarding JavaScript, when clearing an array, I've found two methods:
myArray.length = 0;
vs
myArray = new Array()
I would guess logically myArray.length = 0;
keeps the reference while myArray = newArray()
creates a new reference making previous references void.
However, I have found in the past guessing how JavaScript works by using my own logic has been regularly unsuccessful :)
What's the difference (if any) between the two methods?
Answer
You are correct this time. new Array()
creates a new instance of array and assign it to myArray
.myArray.length = 0
empties an old array while myArray still points to the old array.
Btw, it is better to use []
notation than new Array()
.
I personally always try to use myArray.length = 0;
since it actually empties the content of the array.
No comments:
Post a Comment