input: var a = [2, 3, 5]
Task: we want to fill array with undefineds to 6th element.
output: [2, 3, 5, undefined, undefined, undefined]
ES5 solutions:
-
a.length = 6result:[2, 3, 5, undefined x 3]
Problem: this array has sparse elements (holes) on elements 3-5. We can iterate through it like:for (i = a.length ; i-- ;) {}, but when we iterate like:a.forEach(callback)it only goes through iterable values. -
Classic for loop:
for (i = a.length; i < 6; i++) {a.push(undefined)}
ES6 solutions:
-
ES6
array.prototype.fill(value, startIndex?, endIndex?)a.length = 6; a.fill(undefined, 3, 6); -
ES6
Array.fromthe winner !!a.length = 6; a = Array.from(array);Array.from is great function. Useful to convert
argumentsto real array or to fill holes in sparse arrays:Array.from([2, undefined x 2, 3, undefined x 3])gives[2, undefined, undefined, 3, undefined, undefined, undefined]