javascript - 使用递归函数动态更新数组

标签 javascript arrays

我很难让对象数组显示并动态更新。

预期输出是学生对象数组,每 5 秒更新一次。含义一个新的学生对象将被添加到数组中。

这是我的功能:

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来说明。

(提前感谢您的帮助)

最佳答案

我再次添加了 <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() 函数时,您都会看到学生列表的增长。

    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();

关于javascript - 使用递归函数动态更新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38935996/

相关文章:

javascript - 条件数组解构

c++ - 在类中定义数组的方法和字段

javascript - 在 Canvas 上移动对象

javascript - Javascript 代码与 php 发生错误

java - 零长度数组在内存中是如何表示的?

php切割多维数组

javascript - 如何对对象值数组求和并将它们分配给相关的键名

javascript - Vue 在复制数据后更改数据中的数组

javascript - 如何为每个 WebGL 三 Angular 形设置单独的颜色?

javascript - 需要通过 Google Analytics 跟踪推荐人