我正在学习对象操作,并且正在通过制作一本地址簿来练习#39;获取名称值,将它们添加到对象,将对象加载到数组中,然后输出名称列表。
每当我尝试输出名称列表时,它就会出现如下:
"0: [object Object]; "
我尝试过JSON.stringify但是没有用。如何将对象输出到DOM?我想显示数组中的所有对象。
使用Javascript:
var allInfo = []; //Store names (as objects) here
var output = printList('output');
var cache = [];
var numOfNames = 0;
var nameCounter = 0
alert("JS Works");
function buildList() { //Makes a new object, and pushes it to the 'allInfo' Array
var info = {};
info.firstName = document.getElementById('firstName').value;
info.middleName = document.getElementById('middleName').value;
info.lastName = document.getElementById('lastName').value;
allInfo.push(info);
addName(1);
clear();
alert("Logged");
}
function resetList() {
allInfo = [];
numOfNames = 0;
nameCounter = 0;
addName(0);
blankOut();
}
function blankOut() {
document.getElementById('output').innerHTML = " ";
}
//Problem Function
function generate(o) { //Here is where I am having trouble.
var out = ''; // This is supposed to output a list of names but doesnt.
for (var p in o) {
out += p + ': ' + o[p] + '; ';
}
document.getElementById('output').innerHTML = (JSON.stringify(out, null, 4));
}
function addName(x) {
if (x > 0) {
nameCounter++;
numOfNames = nameCounter;
document.getElementById('numOfNames').innerHTML = numOfNames;
} else {
nameCounter = 0;
numOfNames = 0;
document.getElementById('numOfNames').innerHTML = numOfNames;
}
}
function printList(x) {
var output = getById(x);
return function (text) {
output.innerHTML += text + '\n';
};
}
function getById(x) {
return document.getElementById(x);
}
function clear() {
document.getElementById("firstName").value = "";
document.getElementById("middleName").value = "";
document.getElementById("lastName").value = "";
}
不重复: 不重复。我试图做相反的事情。我试图将所有属性和值FROM和数组/对象输出到DOM。我知道如何抓住'他们从DOM作为其他链接地址,我试图反复排列数组/对象,所以相反。
JSFiddle链接:https://jsfiddle.net/jeffward01/zfv1zy50/
答案 0 :(得分:2)
基本上你必须迭代两次。首先是单个条目。其次是田地。
var allList = [{firstName: "Frank", lastName: "Tester"}, {firstName: "List", lastName: "Tester 2"}];
function generate(list) {
var out = '';
for (var i in list) {
var rec = list[i];
var row = [];
for (var field in rec) {
row.push(field + ': ' + rec[field]);
}
out += "<li>" + row.join(', ') + "</li>";
}
return "<ul>" + out + "</ul>";
}
document.write(generate(allList));
请参阅Fiddle
只是为了得到这个想法。我建议你学习函数式编程。当使用库(下划线,lodash)时,可以使用更少的代码完成此操作; - )