Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate a javascript array shorthand for keys like php

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
like image 375
Sablefoste Avatar asked Nov 04 '12 13:11

Sablefoste


2 Answers

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];
like image 191
David Pärsson Avatar answered Sep 26 '22 02:09

David Pärsson


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.

like image 29
lucideer Avatar answered Sep 22 '22 02:09

lucideer