Posts

Showing posts with the label jsarrays

Initializing an array with values

It is not a frequent use case, but it comes up occasionally: Producing an array [1] of a given length that is filled with values. This blog post explains how to do it and what to watch out for. Let us start with something simple: producing an array of length n whose first element is 0, second element is 1, etc. Array.prototype.map() Once you have an array with length n , you can use the array method map() to fill it appropriately. For example, to produce the array [0, 1, 2] , any array of length 3 will do: > var arr = [null, null, null]; > arr.map(function (x, i) { return i }) [ 0, 1, 2 ] Alas, map() skips holes, but preserves them [2] , which is why an empty array (with only holes) does not work for us: > new Array(3).map(function (x, i) { return i }) [ , , ] The next two sections look at ways of creating an array with a given length. Filling an array via apply() Function.prototype.apply() treats holes as if they were undefined elements [3] . Theref...

Array iteration and holes in JavaScript

The blog post describes how various functions and methods that deal with arrays are affected by holes [1] . Running example All of the code below assumes that the following variable declaration has been made: var arr = [ 'a',, 'b' ]; Above, we have created an array that has the element 'a' at index 0, a hole (no element at all) at index 1 and the element 'b' at index 2. Preliminaries Trailing holes For this blog post, it is important to keep in mind that JavaScript ignores trailing commas in arrays. That means that you need to write two commas to create a trailing hole: > [ 'a', 'b', ] [ 'a', 'b' ] > [ 'a', 'b',, ] [ 'a', 'b', , ] Copying arrays We use slice() to create a copy arr2 of an existing array arr : var arr2 = arr.slice(); The right-hand side of the above assignment is equivalent to: arr.slice(0, arr.length) Array methods forEach() skips hole...

Arrays in JavaScript

Update 2012-12-17: New Sect. 3, “The Array constructor”. This blog post goes deeply into how arrays work in JavaScript: they are much more like objects than you might think. Overview Remember that objects in JavaScript are maps from strings to values. Arrays are objects, only a few property keys are special: Array indices: If a key is a string holding a non-negative integer below a certain maximum then it is treated as an array index. "length" : The value of this property is a non-negative integer holding the length of an array. That length is defined as the numerically largest array index, converted to integer, plus one. This is somewhat shocking, especially when you are coming from another language: array indices in JavaScript are actually strings. Naturally, engines perform optimizations under the hood so that, internally, that is not true. But it is how the spec defines them and how the programmer sees them. For example: > var arr = ['a', ...