简体   繁体   中英

Initializing an array on arbitrary starting index in JavaScript

Is it possible in JavaScript to initialize an array in, for example, subindex 1?

GenderArray: ['Female', 'Male', 'Other'],

I want the Female to be 1 , Male to be 2 and Other to be 3 .

Short answer is no.

It's not possible or at least not in all browsers. For example if you do something like this:

var a = [];

a[1] = "Female";
a[2] = "Male";
a[3] = "Other";

And later access a[0] it will return undefined . When you are initializing array JS engine allocates memory for let's say 20 elements which are indexed from 0.

You can ignore element at 0th index and use your array but please note that in your loops you need to specify starting index as 1 like:

for (var i = 1; i < a.length; i++) { ... }

And also be aware that your array's length will be 4 not 3 as you might expect in this particular case.

Just put in a dummy:

GenderArray: [undefined, 'Female', 'Male', 'Other'],

If you need an arbitrary position in the array use splice() as in:

GenderArray = [];
GenderArray.splice(4, 3, 'Female', 'Male', 'Other');

Which will put them in starting at position 4.

Use JSON. I think json is the best way for using associative arrays:

var myjsonobject = { 1: "Female", 2:"Male",3:"Other"}

Then Call it like this :

 alert(myjsonobject[1]) //for female
 alert(myjsonobject[2]) //for male

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM