Populate a javascript array shorthand for keys like php
Asked Answered
A

6

5

In Javascript, know I can set an array so that the key is a autonumbered (starting at 0) assigned array:

var d_names = new Array("Sunday", "Monday", "Tuesday", 
              "Wednesday", "Thursday", "Friday", "Saturday");

// Key for Sunday is '0' 

and if I want to assign keys, I could do:

    var d_names={};
    d_names[5]="Sunday";
    d_names[6]="Monday";
    d_names[7]="Tuesday";
    d_names[8]="Wednesday";
    d_names[9]="Thursday";
    d_names[10]="Friday";
    d_names[11]="Saturday";

    // Key for Sunday is '5'

But is there a shorthand way to assign the keys like in PHP?

var d_names = new Array(5=>"Sunday", 6=>"Monday", 7=>"Tuesday", 8=>"Wednesday", 
            9=>"Thursday", 10=>"Friday", 11=>"Saturday"); 

// Doesn't work
Applicative answered 4/11, 2012 at 13:55 Comment(3)
why you want start your index from 5?Mosaic
Javascript does not support associative arrays. You can use, however, an object. Albeit the syntax is different.Altercation
To whoever had reviewed the suggested edit: please don't approve it as is, if it overwrites changes from a later edit.Damnable
F
11

What you want is an object:

var d_names = {
    5: "Sunday",
    6: "Monday"
    //...
};

You can then get "Sunday" like this:

var sunday = d_names[5];
Flummox answered 4/11, 2012 at 14:0 Comment(5)
Javascript does not support Associative Arrays... that's an object!Altercation
True, I'm updating my answer. Since JavaScript objects can be used as associative arrays, it's an easy mistake to make.Dinge
Okay, I understand! Then, answer=d_names[5] (if it were an associative array), what would be the javascript equivalent syntax to get answer on key 5?Applicative
The same syntax. I'm updating my answer.Dinge
There is one small issue with this - it's not exactly the same thing as an Array. For example, it has no length property, and you can't push() new values onto the end. If you don't need these (or other) Array-specific features, then this is fine.Peeples
I
3

In PHP, an array with manually defined keys (as opposed to consecutive integers beginning with 0) is called an "associative array" - this is what you have in your example above with '=>' delimiting keys and values.

In Javascript, an "associative array" is technically an "object" (though everything in JS is an object - that's a more detailed topic though).

Shorthand for an "indexed array" (consecutive integer keys) in JS is:

var d_names = [
  'Sunday',
  'Monday',
  // etc.
];

whereas shorthand for an object (like an associative array) in JS is:

var d_names = {
  5: 'Sunday',
  6: 'Monday',
  // etc.
};

You should however be careful when using indexed arrays -vs- objects/associative in Javascript. Javascript is not PHP, and the fact that "everything is an object" has repercussions when looping. A notable difference is that for(var i=0; i<arr.length; ++i){} iterates over an arrays keys but for(var x in obj) {} iterates over an objects "members" which can differ depending on environment/browser/etc.

Infundibuliform answered 4/11, 2012 at 14:4 Comment(0)
H
1

The following in php:

echo json_encode(new Array(5=>"Sunday", 6=>"Monday", 7=>"Tuesday",...11=>"Saturday")); 

Will produce JSON that looks like

   {"5":"Sunday","6":"Monday" , "7":"Tuesday"..."11":"Saturday"}

If sent via ajax and result is json parsed it will return an object:

 obj= { "5": "Sunday", "6": "Monday",....  "11": "Saturday"}

Now you can access using javascript object notation:

 alert( obj['5'] )/* SUnday*/
Hangchow answered 4/11, 2012 at 14:15 Comment(4)
Your 2nd code block doesn't look right. You've fed in an associative array with string values but it's returning an indexed array with objects (with string values).Infundibuliform
Ah, apologies. One more comment on your edit (I think you had this correct previously) - JSON is "stricter" than Javascript in that it doesn't allow integer keys - so PHP will output the keys wrapped in double-quotes. This is purely for JSON though, so somewhat irrelevant to the OP, but no harm mentioning it - it's tripped me up a lot in the past.Infundibuliform
Really? You may have thought me something new... /goes off to research.Infundibuliform
@Infundibuliform numbers are valid however as values. I never use numeric keysHangchow
S
1

There are no associative arrays in JavaScript. You have two choices:

A simple object, used as a (unsorted!) key-value map - easy to write as a literal, also JSON syntax:

{
    "5": "Sunday",
    "6": "Monday",
    "7": "Tuesday",
    "8": "Wednesday",
    "9": "Thursday",
    "10": "Friday",
    "11": "Saturday"    
}

Or you can use a sparse Array, i.e. with no values for the properties 0 to 4. You can easily create it via

var arr = new Array(5); // creates an empty array object with length 5
arr.push("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");

which is equivalent to the literal

[,,,,, "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
Serpentiform answered 4/11, 2012 at 14:24 Comment(1)
very good link on the dangers of trying to use associative arrays in Javascript.Applicative
M
0

Not exactly but you can use an Object

var obj = {

5:"Sunday",
6:"Monday",
7:"Tuesday",
8:"Wednesday",
9:"Thursday",
10:"Friday",
11:"Saturday"    
}

If want to use array

var arr = [];
arr[4] = undefined;
arr.push("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
Mosaic answered 4/11, 2012 at 14:4 Comment(0)
T
0

You can achieve that with this and some other tricks

 var d_names = [,,,,,"Sunday", "Monday", "Tuesday", 
          "Wednesday", "Thursday", "Friday", "Saturday"];

 alert(d_names[5]); //prints "Sunday"
Tripterous answered 4/11, 2012 at 14:6 Comment(1)
Thank you for the response. But this was more of a 'what if'; The days could have been names of pieces of fruit or something else. I am using an index which may not be in numerical order. I have just been fuzzy on the array vs. object thing, but some of the other answers have helped too.Applicative

© 2022 - 2024 — McMap. All rights reserved.