最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

how to Initialize a Javascript Array with non-zero index - Stack Overflow

programmeradmin1浏览0评论

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 mas. [,,....,4321]

basically looking for a short form for:

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

that you can use as a function parameter.

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 mas. [,,....,4321]

basically looking for a short form for:

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

that you can use as a function parameter.

Share Improve this question edited Jun 18, 2012 at 13:10 MandoMando asked Jun 15, 2012 at 18:51 MandoMandoMandoMando 5,5154 gold badges30 silver badges36 bronze badges 2
  • Couldn't you build a loop to pad the array? – j08691 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. – MandoMando Commented Jun 15, 2012 at 18:56
Add a ment  | 

3 Answers 3

Reset to default 9

Something like:

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

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

Pass in something like this:

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

This works:

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

testArray({4: "foo"}); //alerts "foo"
发布评论

评论列表(0)

  1. 暂无评论