使用递归函数动态更新数组
Using a recursive function to dynamically update an array
我很难让我的对象数组显示和动态更新。
预期输出将是一个学生对象数组,每5秒更新一次。这意味着一个新的学生对象将被添加到数组中。
这是我的功能
var students = [];
function getStudents() {
var student = {};
student.name = 'example name';
student.id = 1;
students.push(student);
// recursive
setTimeout(getStudents, 5000);
return students;
}
getStudents();
现在它在数组中创建一个对象,但是停止了。我该怎么做呢?我做错了什么?
点击此处进行说明。
(Thank you for your help advance)
我再次添加了<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();
现在它在数组中创建一个对象,但是会停止。
问题是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/
您只在第一次调用后记录一次。如果将console.log
移动到函数中,它将记录数组每5秒增加一个元素
相关文章:
- JavaScript-保存、存储和更新数组
- 使用ajax(刚刚更改的值)更新数组表
- 如何使用ajax和jquery动态更新数组表
- 使用条件for循环更新数组-Javascript
- 正在RactiveJS上更新数组
- 更新数组中的嵌入文档 - Mongodb + Node Driver
- 余烬更新数组中的对象
- 通过代码+敲除更新数组中的值
- 正在尝试获取事件之外的更新数组的值
- 更新数组后,ng重复双重渲染
- 使用angularjs中复选框的值更新数组
- 将变量推送到数组中,并在每次单击时更新数组
- 如何在Mongoose中从多个数组更新数组内部的值
- 在 ReactJS 中更新数组中对象的最佳方法是什么
- 在 Rally SDK 2 中,如何更新数组字段,例如在变更集的工件上
- 更新数组对象值
- MongoDB 用变量更新数组
- AngularJS - 使用 $http 更新数组内的嵌套对象属性
- JavaScript 使用索引更新数组元素
- 如何更新数组中的所有值?-JS/Jquery.