1

It's a silly question, but is this an array of objects in js?

var test = 
   { 
      Name: "John", 
      City: "Chicago",
      Married: false
   }

if so, how do I declare a new one.. I dont think

var test = new Object();  

or

var test = {}; 

is the same as my example above.

3
  • To create a literal array you use brackets: var test = [1, 2, 3]; Commented Aug 10, 2011 at 13:30
  • 1
    This may confuse you further, or it may make something click for you... this is an array w/ 1 object inside of it var test = [{}]; Commented Aug 10, 2011 at 13:32
  • Yeh! it's a silly question!! why don't just google? Commented Aug 10, 2011 at 13:42

5 Answers 5

10

No.
That's an object with three properties.

The object literal is just a shortcut for creating an empty object and assigning properties:

var test = { };   //or new Object()
test.name = "John";
test.city = "Chicago"
test.married = false;
Sign up to request clarification or add additional context in comments.

1 Comment

Also sometimes called a map with three entries.
6

An array of objects would be

myArray = [
    { prop1 : "val1", prop2 : "val2" },
    { prop1 : "A value", prop2 : "Another value" }
]

You would access the first object's prop2 property like this

myArray[0].prop2

"if so, how do I declare a new one?"

To do what I think you want you would have to create an object like this

var test = function() { 
  this.name = "John"; 
  this.city = "Chicago";
  this.married = false;
}

var test2 = new test();

You could alter the properties like this

test2.name = "Steve";

You can create an array of your objects like this

myArray = [test, test2];

myArray[1].married = true;

Comments

4

No, it's an object.

You could create an array of objects like this:

var array_of_objects = [{}, {}, {}];

For creating new objects or arrays I would recommend this syntax:

var myArray = [];
var myObject = {};

Comments

0

No, test is an object. You can refer to it's instance variables like so:

var myname = test.Name;

Comments

0

It is an object, but you must also understand that arrays are also objects in javascript. You can instantiate a new array via my_arr = new Array(); or my_arr = []; just as you can instantiate an empty object via my_obj = new Object(); or my_obj = {};.

Example:

var test = [];
test['name'] = 'John';
test['city'] = 'Chicago';
test['married'] = false;
test.push('foobar');

alert(test.city); // Chicago
alert(test[0]);  // foobar

2 Comments

alert ( typeof new Array() ); // Object

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.