这让我发疯。我只是想打印出一个数组,但它不起作用。我缺少什么?结果变量返回“未定义”,这很大程度上意味着我的 for 循环无法正常工作。其他一切工作正常,console.log 我正确显示字段已添加到数组中。
// The list of accounts array.
var accountsArray = [];
function addAccount() {
// Take fields and put user data into varables.
var accountName = document.getElementById('accountName').value;
var accountBalance = document.getElementById('accountBalance').value;
var accountType = document.getElementById("accountType");
var accountTypeSelected = accountType.options[accountType.selectedIndex].text;
var accountCurrency = document.getElementById("accountCurrency");
var accountCurrencySelected = accountCurrency.options[accountCurrency.selectedIndex].text;
// Put these variables into the array.
accountsArray.push(accountName);
accountsArray.push(accountBalance);
accountsArray.push(accountTypeSelected);
accountsArray.push(accountCurrencySelected);
// Items added to the array, logged.
console.log('user added: ' + accountsArray);
}
function accountsListHtml() {
var results;
// Loop through the array
for (var i = 0; i < accountsArray.length; i++) {
results = accountsArray[i];
}
document.getElementById('accountsList').innerHTML = results;
}
这是所有文件的链接。这是一个使用 Framework7 的 iOS Web 应用程序。 Balance Pro
最佳答案
您正在 body.onload
中调用 accountsListHtml()
。此时,accountsArray 为空。
我找不到在您链接到的页面上调用 accountsListHtml()
的任何其他可能性。
在函数 addAccount()
中添加一行,它将起作用:
function addAccount() {
/* vour code */
console.log('user added: ' + accountsArray);
accountsListHtml(); // add this line
}
关于Javascript:循环遍历数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26328464/