4

Bash can create a sparse array in one line

names=([0]="Bob" [1]="Peter" [20]="$USER" [21]="Big Bad John")

§ Creating Arrays

Can JavaScript create a sparse array like this?

Zombo
  • 1
  • 62
  • 391
  • 407
  • No, I don't think it can; but I'd like to be proven wrong (if only for academic interest). I'm assuming that creating a function you could call to do this (or extending a prototype) wouldn't qualify as meeting your requirement? – David Thomas Aug 09 '14 at 20:29
  • 1
    Does it count if you wrap it in an IIFE `names = (function(a) { a[2] = 'Bob'; a[22] = 'Fred'; return a;})([]);` -> **http://jsfiddle.net/adeneo/ne3yjoLx/** – adeneo Aug 09 '14 at 21:08
  • Then no, there's no native way to do this, in javascript declarations like in your example code would have to be seperated by semicolons, as spaces wouldn't really count as closing in JS. – adeneo Aug 09 '14 at 21:25
  • @adeneo I think you have misunderstood the question. I am asking if JavaScript has an **analog** to the Bash example above, not a character for character identical command. – Zombo Aug 09 '14 at 21:28

1 Answers1

7

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...

Jason S
  • 13,538
  • 2
  • 37
  • 42