1

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.

1
  • You can use the json instead of array Commented Dec 8, 2011 at 9:43

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

4 Comments

no guarantee undefined is really undefined . For example I can assign undefined a value .
@dan_l So don't :) Simple. And he's ignoring that one anyway. Edit: No you can't. I just tried assigning a value to undefined and it ignored it.
It works on Chrome . undefined = 999; if (undefined) { console.log("yes"); }
@dan_l Sounds like a bug to me, you should report it. And it did not work in firefox.
0

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

2 Comments

I'm sorry, but you are pretty confused. You just created an object, not an array, and it has nothing to do with JSON - that's javascript syntax.
I think JSON full form is JavaScript Obect Notation :)

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.