Bash can create a sparse array in one line
names=([0]="Bob" [1]="Peter" [20]="$USER" [21]="Big Bad John")
Can JavaScript create a sparse array like this?
Bash can create a sparse array in one line
names=([0]="Bob" [1]="Peter" [20]="$USER" [21]="Big Bad John")
Can JavaScript create a sparse array like this?
Technically, JavaScript has a sparse array literal, but it's cumbersome.
var x = [8,,,,4,,,,6]
I don't think you would want to use that as you wouldn't want to count the commas between [1] and [20]. Using objects instead of arrays seems more natural for JavaScript in this case.
var names = {0: "Bob", 1: "Peter", 20: "$USER", 21: "Big Bad John"};
Whether you quote the integers or not, you get the same result -- they're converted to strings to be used as keys in the object (which is basically a hash). (Oh, and I'm not doing anything with your shell variable here.) The same is true for access with []. If you look up names[0] it is actually the same as names['0'] in this case.
However, if you want an actual array, a possible sparse-array-creation function is:
function sparseArray() {
var array = [];
for (var i = 0; i < arguments.length; i += 2) {
var index = arguments[i];
var value = arguments[i + 1];
array[index] = value;
}
return array;
}
var names = sparseArray(0, "Bob", 1, "Peter", 20, "$USER", 21, "Big Bad John");
There's no error checking, so leaving off the final argument would set 21 -> undefined and giving a non-integer key will add it as an object property instead...
In ES2015+, you can create an empty array and then use Object.assign() to populate it sparsely:
const names = Object.assign([],
{0: "Bob", 1: "Peter", 20: "$USER", 21: "Big Bad John"});
This should functionally do exactly the same thing as Jason S's sparseArray() (which is needed before ES2015).
I'll note it is also technically possible to create it as an object and then reset its prototype with Object.setPrototypeOf(names, Array.prototype), but that is likely to interfere with JS engine optimizations down the line because the result wasn't initially created as an array.
names = (function(a) { a[2] = 'Bob'; a[22] = 'Fred'; return a;})([]);-> jsfiddle.net/adeneo/ne3yjoLx