我有这个JSON数据:
var people = [
{ name : "John", age : 25 },
{ name : "Jane", age : 49 },
{ name : "Jim", age : 31 },
{ name : "Julie", age : 39 },
{ name : "Joe", age : 19 },
{ name : "Jack", age : 48 }
];
如何遍历人们内部的所有对象并输出他们的姓名及其年龄,如下所示:
John 25
Jame 49
followed by the rest...
答案 0 :(得分:4)
使用for循环:http://www.w3schools.com/js/js_loop_for.asp
for (var i = 0; i < people.length; i++)
{
document.write(people[i].name + ' ' + people[i].age + '<br />');
}
或jQuery中的each
函数:http://api.jquery.com/jQuery.each/
$.each(people, function(i, o) {
document.write(o.name + ' ' + o.age + '<br />');
});
答案 1 :(得分:3)
不确定如何将其写入页面,但这是document.write
的示例:
for (var i = 0, ilen = people.length; i < ilen; i++)
{
document.write(people[i].name + ' ' + people[i].age + '<br/>');
}
我强烈建议在for循环的第一个表达式中获取长度,而不是第二个。在这种情况下,people.length
并不太贵。但是如果代价高昂且你将它放在第二个表达式中,就像for (var i = 0; i < people.length; i++)
一样,那么它将在每个循环中进行评估,你想知道你的CPU在哪里周期过去了。 :)
答案 2 :(得分:2)
使用jquery,你可以做到
$.each(people, function(){
alert(this.name + " " + this.age);
});
如果您想将其附加到div,则可以执行
$.map(people, function(){
return this.name + " " + this.age + "<br/>";
}).appendTo("#myDiv");
答案 3 :(得分:1)
循环通过它们。这些是Javascript对象文字而不是JSON,只是FYI
for(var i = 0; i < people.length; i++) {
alert(people[i].name + " " + people[i].age)
}
例如:
var variable = { 'key': 'value' }; // object
console.log(variable.key); // outputs: value
var json = '{"key":"value"}'; // javascript string representing valid json
console.log(json.key); // outputs: undefined
var jObj = JSON.parse(json); // now a javascript object from the json string
console.log(jObj.key); // outputs: value
所以JSON只存在于javascript中作为表示。
答案 4 :(得分:0)
我使用forEach
:
people.forEach(function(person) {
console.log(person.name, person.age)
});
答案 5 :(得分:0)
以下是使用jquery的示例:
var people = [
{ name : "John", age : 25 },
{ name : "Jane", age : 49 },
{ name : "Jim", age : 31 },
{ name : "Julie", age : 39 },
{ name : "Joe", age : 19 },
{ name : "Jack", age : 48 }
];
jQuery.each(people, function(index, person){
console.log([person.name, person.age].join(" ")) ;
});
输出:
John 25
Jane 49
Jim 31
Julie 39
Joe 19
Jack 48
答案 6 :(得分:0)
你去吧
正在使用 demo
标记
<div id="people"></div>
JS
var people = [
{ name : "John", age : 25 },
{ name : "Jane", age : 49 },
{ name : "Jim", age : 31 },
{ name : "Julie", age : 39 },
{ name : "Joe", age : 19 },
{ name : "Jack", age : 48 }
];
$(function(){
var $people = $("#people");
$.each(people, function(){
$people.append("<div>").append("<span>"+this.name+"</span>"+this.age+"<br />");
});
});
的CSS
#people
{
width:70px;
text-align:right;
}
#people span
{
float:left;
}