我很难让我的对象数组显示并动态更新。
预期输出将是一个学生对象数组,每5秒更新一次。含义新的学生obj将被添加到数组中。
这是我的功能:
var students = [];
function getStudents() {
var student = {};
student.name = 'example name';
student.id = 1;
students.push(student);
// recursive
setTimeout(getStudents, 5000);
return students;
}
getStudents();
现在它在数组中创建了一个对象,但是停止了。我怎样才能做到这一点?我做错了什么?
Fiddle here来说明。
(提前感谢您的帮助)
答案 0 :(得分:1)
同样,我添加了<div id="test">
元素来收集输出。
<div id="test">
</div>
我创建了一些数组,以便我可以使用数据。
// Here's an array of students we can add for test purposes...
//
var arrStudents = [ "Rita", "Sue", "And", "Bob", "too" ];
var arrIDs = [ 123, 234, 345, 456, 567 ];
// We can populate 5 students with the above data, this will
// keep track of the number of students added.
//
var intStudents = 0;
var students = [];
我创建了updateTest()
函数递归调用的函数getStudents()
:
function updateTest() {
var a;
document.getElementById('test').innerHTML = "";
for (a = 0; a < students.length; a++) {
// Append the output to innerHTML
//
document.getElementById('test').innerHTML +=
a.toString() +
": Student name: " + students[a].name +
", ID: " + students[a].id + "<br />";
}
}
现在每次调用updateTest()
函数时都会调用getStudents()
,您就会看到学生名单增长。
function getStudents() {
var student = {};
if (intStudents < 5) {
// Add one of the students from our arrays.
//
student.name = arrStudents[intStudents];
student.id = arrIDs[intStudents];
}
else {
// Just keep adding this when we run out of students.
//
// We can still use intStudents to generate a unique
// name and id.
//
student.name = 'example name ' + intStudents.toString();
student.id = intStudents;
}
intStudents++;
students.push(student);
// recursive
setTimeout(getStudents, 5000);
// call updateTest() each time to update the div...
//
updateTest();
}
getStudents();
答案 1 :(得分:0)
现在它在数组中创建了一个对象,但是停止了。
问题是console.log(students)
在递归函数调用之外被调用一次。在递归函数
console.log(students)
function getStudents() {
var student = {};
student.name = 'example name';
student.id = 1;
students.push(student);
console.log(students);
// set recruive
setTimeout(getStudents, 5000);
}
jsfiddle https://jsfiddle.net/88r0rj8n/3/
答案 2 :(得分:0)
您只需在第一次通话后记录一次。如果在函数内部移动console.log
,它将每5秒将数组记录一个元素