【发布时间】:2015-10-28 22:44:56
【问题描述】:
我正在学习对象操作,并正在通过制作一个“地址簿”来练习,它接受名称值,将它们添加到对象中,将对象加载到数组中,然后输出名称列表。
每次我尝试输出名称列表时,结果如下:
"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 = "";
}
不重复: 不是重复的。我正试图做相反的事情。我正在尝试将所有属性和值从和数组/对象输出到 DOM。我知道如何从 DOM 中“抓取”它们作为其他链接地址,我试图反刍数组/对象,所以相反。
JSFiddle 链接在这里:https://jsfiddle.net/jeffward01/zfv1zy50/
【问题讨论】:
-
不是重复的。我正试图做相反的事情。我正在尝试将所有属性和值从和数组/对象输出到 DOM。我知道如何从 DOM 中“抓取”它们作为其他链接地址,我试图反刍数组/对象,所以相反。
-
你告诉 JS 打印出对象。您必须手动取出字段(名字、姓氏等...)。编写一个函数来为你做这件事。
-
我以为我用了'for(p in o)'
-
我假设 o 是包含所有记录的列表 (allInfo)。是吗?
标签: javascript jquery arrays sorting object