开发者

Array of objects in js?

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.


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;


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;


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 = {};


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

var myname = test.Name;


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜