Javascript associative arrays

  • rtm223
  • Mastermind
  • Mastermind
  • User avatar
  • Posts: 1855
  • Loc: Uk

Post 3+ Months Ago

I've got an array in JS that looks like this:
Code: [ Select ]
startColor=new Array();
  startColor['r']=51;
  startColor['g']=51;
  startColor['b']=51;
  1. startColor=new Array();
  2.   startColor['r']=51;
  3.   startColor['g']=51;
  4.   startColor['b']=51;

In PHP I would have coded it like:
PHP Code: [ Select ]
 
startColor=array(
 
    'r' => 51,
 
    'g' => 51,
 
    'b' => 51,
 
);
  1.  
  2. startColor=array(
  3.  
  4.     'r' => 51,
  5.  
  6.     'g' => 51,
  7.  
  8.     'b' => 51,
  9.  
  10. );

Can't seem to find a similar shorthand for javascript anywhere. Just wondering if it exists?
  • Anonymous
  • Bot
  • No Avatar
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post 3+ Months Ago

  • RichB
  • Guru
  • Guru
  • User avatar
  • Posts: 1121
  • Loc: Boston

Post 3+ Months Ago

I'm not sure if there is an equivalent shorthand declaration specifically for arrays, but I think you can use objects as associative arrays:

Code: [ Select ]
<script type="text/javascript">
<!--
myObj = {
    r : 51,
    g : 51,
    b : 51
}

alert("myObj['r'] = " + myObj["r"]);

//or
alert("myObj.r = " + myObj.r);

//or to loop
for(i in myObj){
            alert(i + " = " + myObj[i]);
}
// -->
</script>
  1. <script type="text/javascript">
  2. <!--
  3. myObj = {
  4.     r : 51,
  5.     g : 51,
  6.     b : 51
  7. }
  8. alert("myObj['r'] = " + myObj["r"]);
  9. //or
  10. alert("myObj.r = " + myObj.r);
  11. //or to loop
  12. for(i in myObj){
  13.             alert(i + " = " + myObj[i]);
  14. }
  15. // -->
  16. </script>
  • rtm223
  • Mastermind
  • Mastermind
  • User avatar
  • Posts: 1855
  • Loc: Uk

Post 3+ Months Ago

Works like a charm, thanks :D

Post Information

  • Total Posts in this topic: 3 posts
  • Users browsing this forum: No registered users and 57 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.