所以我试图用逗号打印一行中所有的朋友数组的名字,(我正在尝试学习JS和JSON,并且编程知识非常少) 这是我的互联网数据文件 http://www.json-generator.com/
我的阵列 [ { "年龄":25, " eyeColor":" blue", "姓名":" Leon Pickett", "电话":" +1(834)535-2787", "平衡":" $ 3,632.41", "地址":" 856 Woodhull Street,Southmont,Wisconsin,373", "朋友":[ {" id":0," name":" Bonnie Dudley"}, {" id":1," name":" Blair Hopkins"}, {" id":2," name":" Burris Lara"} ],}, { "年龄":29, " eyeColor":" brown", "姓名":" Rosales Raymond", "平衡":" $ 3,632.41", "电话":" +1(935)462-3887", "地址":" 745 Havens Place,Norvelt,Florida,6999", "朋友":[ {" id":0," name":" Theresa Burt"}, {" id":1," name":" Mooney Whitney"}, {" id":2," name":" Hebert Gill"} ]}]
这是我的代码
var xmlhttp = new XMLHttpRequest();
var txt = "jsontst1.txt";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", txt, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var out2 = "";
var i, j;
for (i = 0; i < arr.length; i++) {
var frndlngth = arr[i].friends.length;
for (j = 0; j < frndlngth; j++) {
var frnds = arr[i].friends[j];
out2 += frnds.name;
}
out +=
"Name = " + arr[i].name + "<br>" +
"Age = " + arr[i].age + "<br>" +
"Phone = " + arr[i].phone + "<br>" +
"Balance = " + arr[i].balance + "<br>" +
"Eyecolor = " + arr[i].eyeColor + "<br>" +
"Address = " + arr[i].address + "<br>" +
"Friends = " + out2 + "<hr>";
}
document.getElementById("id01").innerHTML = out;
}
&#13;
在输出中Friends还显示上一个数组的值?我在这做错了什么?
答案 0 :(得分:0)
您可以使用
var stringresult = JSON.stringify(yourobject或array);
现在你可以打印或提醒它像alert(stringresult)。
答案 1 :(得分:0)
原因是out2
变量是全局的,因此值被附加在其中,而不是在外循环后重置它。
在for-loop
function myFunction(arr) {
var out = "";
var i, j;
for (i = 0; i < arr.length; i++) {
var out2 = "";
var frndlngth = arr[i].friends.length;
for (j = 0; j < frndlngth; j++) {
var frnds = arr[i].friends[j];
out2 += frnds.name;
}
out +=
"Name = " + arr[i].name + "<br>" +
"Age = " + arr[i].age + "<br>" +
"Phone = " + arr[i].phone + "<br>" +
"Balance = " + arr[i].balance + "<br>" +
"Eyecolor = " + arr[i].eyeColor + "<br>" +
"Address = " + arr[i].address + "<br>" +
"Friends = " + out2 + "<hr>";
}
document.getElementById("id01").innerHTML = out;
}
var input = [{
"age": 25,
"eyeColor": "blue",
"name": "Leon Pickett",
"phone": "+1 (834) 535-2787",
"balance": "$3,632.41",
"address": "856 Woodhull Street, Southmont, Wisconsin, 373",
"friends": [{
"id": 0,
"name": "Bonnie Dudley"
}, {
"id": 1,
"name": "Blair Hopkins"
}, {
"id": 2,
"name": "Burris Lara"
}],
}, {
"age": 29,
"eyeColor": "brown",
"name": "Rosales Raymond",
"balance": "$3,632.41",
"phone": "+1 (935) 462-3887",
"address": "745 Havens Place, Norvelt, Florida, 6999",
"friends": [{
"id": 0,
"name": "Theresa Burt"
}, {
"id": 1,
"name": "Mooney Whitney"
}, {
"id": 2,
"name": "Hebert Gill"
}]
}];
myFunction(input);
&#13;
<div id="id01"></div>
&#13;