我在Javascript中有一个对象。例如......:
vehicle.image.jpg.large = "mylargejpg.jpg";
或
vehicle.image.jpg.small = "mysmalljpg.jpg";
然后我有一个变量
var imageType = "jpg.small";
如何使用“imageType”变量??
动态返回该对象的值IE:vehicle.image \ imageType;或任何会返回“mysmalljpg.jpg”
答案 0 :(得分: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");