我有以下对象: (使用此代码获取内容:)
alert(JSON.stringify(objData));
{"food":[{"name":"Belgian Waffles","price":"$5.95","description":"Two of our famous Belgian Waffles with plenty of real maple syrup","calories":"650"},{"name":"Strawberry Belgian Waffles","price":"$7.95","description":"Light Belgian waffles covered with strawberries and whipped cream","calories":"900"},{"name":"Berry-Berry Belgian Waffles","price":"$8.95","description":"Light Belgian waffles covered with an assortment of fresh berries and whipped cream","calories":"900"},{"name":"French Toast","price":"$4.50","description":"Thick slices made from our homemade sourdough bread","calories":"600"},{"name":"Homestyle Breakfast","price":"$6.95","description":"Two eggs, bacon or sausage, toast, and our ever-popular hash browns","calories":"950"}]}
我是 JavaScript 的新手,想获取一些值,例如“Homestyle Breakfast”(最后一个)的所有值
thisResult = '';
thisResult += 'Name: ' + objData.food.name;
thisResult += '\nPrice: ' + objData.food.price;
thisResult += '\nDescription: ' + objData.food.description;
thisResult += '\nCalories: ' + objData.food.calories;
alert(thisResult);
为什么该代码不起作用? 我没有得到该代码的任何信息。
最佳答案
那个 (food
) 是一个数组,所以你应该迭代它或者你应该知道你需要显示哪个键。例如,如果您想要最后一个,您应该将 objData.food
更改为 objData.food[4]
或 objData.food[objData.food.length - 1]
你可以循环它:
for (var i = 0; i < objData.food.length; i++) {
var food = objData.food[i];
// for example display only that with name = Homestyle Breakfast
if (food.name === 'Homestyle Breakfast') {
thisResult = '';
thisResult += 'Name: ' + food.name;
thisResult += '\nPrice: ' + food.price;
thisResult += '\nDescription: ' + food.description;
thisResult += '\nCalories: ' + food.calories;
}
}
关于javascript - 从对象中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32136271/