开发者

Accessing Javascript variable stored in an array

I currently have an array as follows:

var allMenus = ['vehicleMakeFb','vehicleModelFb','vehicleTrimFb']

Where vehicleMakeFb etc. are actually objects. I originally tried to store the objects in the array, but I un开发者_开发问答derstand this is not possible in JS, so I have resorted to storing the names of the variables as strings.

My intention is to be able to iterate through the variables, and get individual properties of each, such as:

for (fbMenu in allMenus) {
    alert(vehicleMakeFb.divId);
}

Where divId is a string.

What is the correct syntax to access this variable by its name?


What do you mean you can't store an array of objects?

var allMenus = [
  {make: 'Ford', model: 'Mustang', trim: 'Coupe'},
  {make: 'Ford', model: 'Explorer', trim: 'Eddie Bauer'}
];

// all items
for (var i = 0; i < allMenus.length; i++){
  var fbMenu = allMenus[i];

  // explicit list of properties
  console.log('[X] Make: ' + fbMenu.make);
  console.log('[X] Model: ' + fbMenu.model);
  console.log('[X] Trim: ' + fbMenu.trim);

  // discovered list of properties
  for (var prop in fbMenu){
    console.log('[D] ' + prop + ': ' + fbMenu[prop]);
  }
}


You can access object properties in two ways:

Dot Notation

object.prop

Brackets

object['prop']

You can store objects in an array.

var arrayFullOfObjects = [{
   foo: 'bar'
},
  window,
  jQuery
];

arrayFullOfObjects[0].foo; //bar


You can access the value of a property of a JS object using any of the following syntax:

// assuming the following object
var company = { employee : { name : 'foo' }  };

// we can access the name property via
var name1 = company.employee.name;
var name2 = company.employee['name'];
var name3 = company['employee']['name'];
// ...

You can then store objects into arrays in much the same way:

var obj1, obj2, obj3; // some objects (initialized prior)
var myArray = [obj1, obj2, obj3];

Looking at your code, just make sure you ditch the quotes on your array JSON. (i.e. [obj], not ['obj']).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜