Creating a sparse array in one line
Technically, JavaScript has a sparse array, but it's cumbersome.
var x = [8,,,,4,,,,6]
I don't think you would like to use this as you would not want to count commas between [1] and [20]. In this case, using objects instead of arrays seems more natural to JavaScript.
var names = {0: "Bob", 1: "Peter", 20: "$USER", 21: "Big Bad John"};
Whether you supply integers or not, you get the same result - they are 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 names[0]
, in this case it will be the same as names['0']
.
However, if you want to get a real array, it is possible to create a sparse array:
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 is no error checking, so leaving the final argument will be set to 21 undefined
-> and issuing a non-integer key will add it as an object property ...
source to share