Loading ...
Sorry, an error occurred while loading the content.

2978[jslint] Re: Array construction bug

Expand Messages
  • Alexandre Morgaut
    Aug 31, 2012
    • 0 Attachment
      --- In jslint_com@yahoogroups.com, Joe Hansche <madcoder@...> wrote:
      > According to MDN that is not what actually happens:
      > https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/length
      > 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.

      The MDN documentation is unfortunately not very clear on this page.
      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()
    • Show all 21 messages in this topic