2

I'm passing an array to a function and I'm curious if there is a quick way to use the json style array initializer to pass an anonymous array:

e.g.:

myfunction([1,2,3,4]);

Is there some special syntax in javascript that would allow one to initialize the array with non-zero index?

for example, instead of

myfunction([,,,,4321]);

//array[4] == 4321 here

but if you have an array that has the first 100 positions undefined, you would have to have 100 commas. [,,....,4321]

basically looking for a short form for:

var a = new Array(); a[100] = 4321; 

that you can use as a function parameter.

2
  • Couldn't you build a loop to pad the array? Commented Jun 15, 2012 at 18:53
  • @j08691 not sure how one can loop an anonymous array. it'd be easier to define the variable upfront which is what I'm trying to avoid. Commented Jun 15, 2012 at 18:56

3 Answers 3

9

Something like:

var a = new Array(100).concat([4321]);
Sign up to request clarification or add additional context in comments.

1 Comment

Nice. this should work for more than one entry as well: myfunction(new Array(100).concat([4321], new Array(20), [65433], new Array(999), [234], ...));
3

Probably shortest approach (but very unreadable) would be

(a = [])[100] = 4321;

But still you can't use that directly as a function parameter, as it returns the added element, and not the entire array. You still have to call as myFunction(a).

Comments

3

Pass in something like this:

myfunction({100: "foo", 101: "bar"});

This works:

function testArray(arr) {
    alert(arr[4]);
}

testArray({4: "foo"}); //alerts "foo"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.