2978[jslint] Re: Array construction bug
- Aug 31, 2012--- In firstname.lastname@example.org, Joe Hansche <madcoder@...> wrote:
>The MDN documentation is unfortunately not very clear on this page.
> According to MDN that is not what actually happens:
> You can only truncate an array's length. Artificially increasing an array's
> "length" still serves no purpose if you don't initialize what's *in* it.
It says that "the array still contain only 2 elements".
It's true, as when you do "new Array(50)" the array will be physically empty, only its length property will be impacted.
Setting a specific length is still not useless. It has an impact on many of its methods like pop(), push(), shift(), unshift(), splice(), concat(), ...
It is often used also to fill a string
var arr, str;
arr = ;
arr.length = 51;
str = arr.join('0'); // generate a string with 50 "0"
But for performance concerns it won't always help with methods like map(callback)
"callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values."
So if map is called on an array with length of 50 and with only 3 filled elements, the resulting array will have the same length but the callback will be called only 3 times and you won't be able to fill the other elements of this array via map()
- << Previous post in topic Next post in topic >>