再び、出力を収集するために<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 = [];
私は再帰的にgetStudents()
関数によって呼び出される関数updateTest()
を作成しました:
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 />";
}
}
は今getStudents()
関数が呼び出される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();
コードは正常に動作します。各配列ではなく、最初の反復の後でのみ配列を記録します。 – lexith