我有这样的对象
[Object {
image =
"images/item-1.png"
, heading =
"Careers"
, text =
"Lorem ipsum dolor sit a...ctetur adipiscing elit."
},
Object {
image =
"images/item-2.png"
, heading =
"Contact Us"
, text =
"Morbi tincidunt commodo scelerisque."
},
Object {
image =
"images/item-3.png"
, heading =
"About Us"
, text =
"Duis porttitor diam vitae leo elementum accumsan."
}]
我如何从这个对象中提取价值。?
我正在尝试使用$ .each但未获得正确结果来实现此目的。我的要求是在单独的变量中获取图像URL,标题和文本。 请帮助我。
答案 0 :(得分:4)
你可以这样做:
var arr = [{
"image": "images/item-1.png",
"heading": "Careers",
"text": "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
}, {
"image": "images/item-2.png",
"heading": "Contact Us",
"text": "Morbi tincidunt commodo scelerisque."
}, {
"image": "images/item-3.png",
"heading": "About Us",
"text": "Duis porttitor diam vitae leo elementum accumsan."
}]
$.each(arr, function (index, value) {
var image_url = value.image;
var heading = value.heading;
var text = value.text;
console.log(index, image_url, heading, text);
});
答案 1 :(得分:2)
我不喜欢使用$.each
,因为与简单的for循环相比,jQuery开销很大,可以实现同样的目的。
for (var i = 0; i < arr.length; i++)
{
var image_url = arr[i].image,
heading = arr[i].heading,
text = arr[i].text;
// Do stuff with variables
}