在显示为空白的数组中打印对象

问题描述 投票:0回答:2
function displayEvent(array) {
var vOutput = "";
var ind = 0;
for(var i = 0; i < array.length; i++) {
    ind += 1;
    vOutput += "Name " + ind + ": " + array[i].name + ", Age " + array[i].age + "<br />";
    }
    document.getElementById("output").innerHTML = vOutput;
}
function init() {
var arrEvent = [];
var objEvent = {};
objEvent.name = prompt("Enter name of Event");
objEvent.age = prompt("Enter number of Guests");
arrEvent.push(objEvent);
while(objEvent.name.length > 0) {
    objEvent.name = prompt("Enter name of Event");
    objEvent.age = prompt("Enter number of Guests");
    if(objEvent.name.length > 0) {
        arrEvent.push(objEvent);
    }
}
displayEvent(arrEvent);
}
window.onload = init;

[尝试将对象数组打印到HTML段落ID中,并且每当我执行上述代码时,我都会得到正确的输出,但数组元素只是显示为空白。

javascript html arrays object output
2个回答
0
投票

您面临对象引用更新的问题。您可以通过

解决此问题
function displayEvent(array) {
var vOutput = "";
var ind = 0;
for(var i = 0; i < array.length; i++) {
 ind += 1;
 vOutput += "Name " + ind + ": " + array[i].name + ", Age " + array[i].age + "<br />";
}
document.getElementById("output").innerHTML = vOutput;
}
function init() {
var arrEvent = [];
var objEvent = {};
objEvent.name = prompt("Enter name of Event");
objEvent.age = prompt("Enter number of Guests");
arrEvent.push(Object.assign({}, objEvent));
while(objEvent.name.length > 0) {
 objEvent.name = prompt("Enter name of Event");
 objEvent.age = prompt("Enter number of Guests");
 if(objEvent.name.length > 0) {
    arrEvent.push(Object.assign({}, objEvent));
 }
}
 displayEvent(arrEvent);
}
window.onload = init;

您可以克隆您的对象,然后将其压入数组,因此将删除主要对象的引用,并且objEvent将充当下一个输入的新对象。


0
投票

您总是将同一个对象推入数组。

更改为:

function displayEvent(array) {
var vOutput = "";
var ind = 0;
for(var i = 0; i < array.length; i++) {
    ind += 1;
    vOutput += "Name " + ind + ": " + array[i].name + ", Age " + array[i].age + "<br />";
    }
    document.getElementById("output").innerHTML = vOutput;
}
function init() {
var arrEvent = [];
var name = '';
var age = '';
name = prompt("Enter name of Event");
age = prompt("Enter number of Guests");
arrEvent.push({name: name, age: age});
while(objEvent.name.length > 0) {
    name = prompt("Enter name of Event");
    age = prompt("Enter number of Guests");
    if(objEvent.name.length > 0) {
        arrEvent.push({name: name, age: age});
    }
}
displayEvent(arrEvent);
}
window.onload = init;
© www.soinside.com 2019 - 2024. All rights reserved.