-2

I want to create an array for javascript

var person = {firstName:"John", lastName:"Doe", age:46};
var person = {firstName:"Peter", lastName:"Toh", age:20};

For example I want to create

person[1].firstName return me John
person[2].firstName return me Peter

How do I actually declare my javascript to make the 2 element works.

Baoky chen
  • 99
  • 2
  • 10
  • Erm... `var person = [{firstName:"John"},{firstName:"Peter"}];` gives `person[0].firstName` as `John`. Note that arrays are zero-based. – Niet the Dark Absol Nov 12 '14 at 15:36
  • sorry i forgot the 0 refer to element 1. – Baoky chen Nov 12 '14 at 15:39
  • There are many good JavaScript tutorials available on the Internet. I recommend MDN: [MDN - Arrays](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Predefined_Core_Objects#Array_Object). – Felix Kling Nov 12 '14 at 15:51

2 Answers2

2

You aren't creating an associative array, you are creating an array of objects. You can either initialize it with an array literal:

var person = [
     {firstName:"John", lastName:"Doe", age:46},
     {firstName:"Peter", lastName:"Toh", age:20}
];

(keep in mind that arrays in javascript start with zero, so person[0] will be John and person[1] will be Peter).

or you can create an empty array and then add the entries afterwards. This allows you to choose the indexes freely:

var person = [];
person[1] = {firstName:"John", lastName:"Doe", age:46};
person[2] = {firstName:"Peter", lastName:"Toh", age:20};
Philipp
  • 67,764
  • 9
  • 118
  • 153
0

Use an array literal to create an Array:

var persons = [{firstName:"John", lastName:"Doe", age:46},
               {firstName:"Peter", lastName:"Toh", age:20}];

Notice that arrays are zero-indexed in JavaScript, so you'd access it like this:

person[0].firstName; // John
person[1].firstName; // Peter

See also What are the best practices to follow when declaring an array in Javascript? and JavaScript Object Literals & Array Literals.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375