deniz
deniz

Reputation: 2567

Javascript defining array. "arrayception"

I am trying to create a list of "items" in a canvas game. For example, an array named list. Each element must contain the information about each item. First element will contain something different. I will remove first one with 'shift()' command. Like :

list.shift(); 
list[0]['name']
list[0]['id']
list[0]['x']
list[0]['y']
list[1]['name']
list[1]['id']
list[1]['x']
list[1]['y']

but i don't know how to define something like this. normally i define arrays like

{"name" : xx, "id" : 5 ... }

but this works like :

list['name']
list['id']

Upvotes: 1

Views: 330

Answers (2)

KooiInc
KooiInc

Reputation: 122906

use:

var list = [];
list[0] = {name: 'xx', id: 0, /*etc*/};
list[1] = {name: 'yy', id: 1, /*etc*/};

it creates an array of objects. You can use it like this:

var first = list.shift();
first.name; //=> xx
//or
var first = list[0];
first.name; //=> xx 

Note: using {...} (Object literal) creates an Object, not an Array. An array can be created using an Array literal: [...]. Although an object is sometimes said to be an Associative Array, it is not an Array object, so things like {...}.shift() will not work for Objects.

Upvotes: 2

mpm
mpm

Reputation: 20155

There are no associative arrays in javascript. so for instance , when you do

var _array = []
_array["field1"] ="value";

you are actually adding a property to the _array object .

_array.field1 = value <=> _array["field1"] ="value";

so if you want to create a collection of objects , do

var collection =[];
var myObject = {"field1":"value1"};
collection.push(myObject);

Upvotes: 1

Related Questions