Javascript:循环遍历数组

标签 javascript arrays

这让我发疯。我只是想打印出一个数组,但它不起作用。我缺少什么?结果变量返回“未定义”,这很大程度上意味着我的 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/

相关文章:

javascript - Casperjs ajax 调用 - waitForResource 和解析错误

javascript - C# 如何将复杂的 JSON 对象的子对象转换为模型

javascript - 等待图像加载到下划线模板中

python - 直观地解释这个 4D numpy 数组索引

c - strcmp 未正确比较指向字符的指针数组中的 2 个相邻字符串

ruby-on-rails - 如何将多级数组中的唯一值映射到 value=>array 的散列?

javascript - JS DOM 操作如何影响 CSS 规则匹配?

javascript - Angular 服务无法执行功能

arrays - 在数组中的指定索引位置添加元素。电源外壳

javascript - 如果要循环的数组未定义,如何在 JavaScript 的 for 循环中设置空数组?