1

I have an object in Javascript. For example...:

vehicle.image.jpg.large = "mylargejpg.jpg";

or

vehicle.image.jpg.small = "mysmalljpg.jpg";

I then have a variable

var imageType = "jpg.small";

How can I dynamically return the value of that object using the "imageType" variable??

IE: vehicle.image\imageType; or whatever would return "mysmalljpg.jpg"

4

1 回答 1

4

你想遍历你的对象......

// Takes an object and a path to some element and traverses the object
function traverse(obj, path) {
  // split the path into pieces 
  var links = path.split(".");

  // traverse the object - one level at a time 
  for (var x = 0; x < links.length; ++x) 
    obj = obj[links[x]];

  return obj;
}

traverse(vehicle.image, "jpg.small");
于 2013-09-26T03:12:51.677 回答