1

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']
1
  • { ... } is not an array, it's an object (literal). Commented Mar 10, 2012 at 8:32

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

how can i send this through websockets using JSON.stringify ?
You can just serialize the list object
for the example of my answer: var liststr = JSON.stringify(list) returns "[{"name":"xx","id":0},{"name":"yy","id":1}]", var list2 = JSON.parse(liststr) converts the string back to the array of obects. The string can be sent through websockets I suppose, that's out of the realm of this question.
thanks for the answer. i will look through it a bit. by the way i have learnt that [] is array, {} is object. thanks. so i will define objects in [] and send that.
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.