我是初学者,它会显示 :( 但有人能帮我找到正确的方向吗?我有一个对象字面量,里面嵌套了数组。我需要获取数组的第一行,然后推送它的值row 进入三个不同的输入。然后在 5 秒后,它会超时,然后显示下一个数组行。JSfiddle 供引用 https://jsfiddle.net/sqj3jz4p/
<div>
<label for="votes1">Votes for Candidate 1</label> <input
type="number" class="count" id="votes1" readonly>
</div>
<div>
<label for="votes2">Votes for Candidate 2</label> <input type="number"
class="count" id="votes2" readonly>
</div>
<div>
<label for="votes3">Votes for Candidate 3</label> <input type="number"
class="count" id="votes3" readonly>
</div>
var votingData = {
voting: [
[
336122, 612446, 711326
],
[
4663122, 7001244, 822506
],
[
10437916, 12443910, 930971
],
[
17623004, 18680779, 1060304
],
[
24179347, 21991292, 1175930
]
]
};
function updateVoteCount(array) {
"use strict";
for (var i = 0, l = votingData.voting.length; i < l; i++) {
var voteArray = votingData.voting[i];
console.log(voteArray);
document.getElementById("votes1").value = voteArray[0];
document.getElementById("votes2").value = voteArray[1];
document.getElementById("votes3").value = voteArray[2];
}
}
var timeDelayMs = 5000; // 5-second delay
function voteUpdates(voting,myIndex) {
"use strict";
if ( voting.length > myIndex ) {
updateVoteCount(voting[myIndex]);
setTimeout(voteUpdates, timeDelayMs, voting, myIndex+1);
}
}
voteUpdates(voting[0]);
最佳答案
您的代码存在一些问题,例如 setTimeOut
的使用和 voteUpdates
函数的参数。查看带有修复的代码版本:
var votingData = {
voting: [
[336122, 612446, 711326],
[4663122, 7001244, 822506],
[10437916, 12443910, 930971],
[17623004, 18680779, 1060304],
[24179347, 21991292, 1175930]]
};
function updateVoteCount(voteArray) {
document.getElementById("votes1").value = voteArray[0];
document.getElementById("votes2").value = voteArray[1];
document.getElementById("votes3").value = voteArray[2];
}
var timeDelayMs = 5000; // 5-second delay
function voteUpdates(voting, myIndex) {
if ( myIndex < voting.length) {
updateVoteCount(voting[myIndex]);
setTimeout(function() { voteUpdates(voting, myIndex+1) }, timeDelayMs);
}
}
voteUpdates(votingData.voting, 0);
<div>
<label for="votes1">Votes for Candidate 1</label> <input
type="number" class="count" id="votes1" readonly>
</div>
<div>
<label for="votes2">Votes for Candidate 2</label> <input type="number"
class="count" id="votes2" readonly>
</div>
<div>
<label for="votes3">Votes for Candidate 3</label> <input type="number"
class="count" id="votes3" readonly>
</div>
关于javascript - 从嵌套数组中获取一行,将值插入输入,然后 setTimeout 更改为下一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45067190/