【问题标题】:Why doesn't my 'for' statement loop and the if statement inside it execute?为什么我的“for”语句循环和其中的 if 语句不执行?
【发布时间】:2015-05-18 23:37:13
【问题描述】:

我有一个函数,它有一个重复的 for 语句,直到变量 (i) 等于 localStorage.length 并且在 for 循环内有一个 if 语句检查 localStorage 条目是否以 # 开头,然后运行一个函数.当我调用此函数时,for 循环中的任何内容都不会运行。

function refresh() {
  var i = 0;

  console.info("The LocalStorage Length is: " + localStorage.length);
  console.info("i is: " + i);
  console.log("i == localStorage.length is:" + i == localStorage.length);

  for (i = 0; i == localStorage.length; i++) {
    console.info("i is: " + i);

    current = localStorage.key(i);
    if (current.substr(0, 1) == "#") {
      noteArea.innerHTML = +createHtml(current.substr(1), localStorage.getItem(current)); //Adds the html to the page
      console.log(current.substr(1) + " - Note displayed."); //Logs the note title
    } else {
      console.log("No notes saved.");
    }

    console.info("i == localStorage.length is:" + i == localStorage.length);
  }
}


function createHtml(name, desc) {
  var html = "<div class = 'note'> <h4 class = 'note-title'>" + name + "</h5> <p class = 'note-desc'>" + desc + "</p> </div> <br/>";

  console.log(html);
  return html;
}

【问题讨论】:

  • 您忘记发布代码了吗?
  • 看起来他点击提交太快了,他在一个句子中间。
  • 在你发布代码之前,我帮不了你
  • 任何代码或线索你在说什么?
  • localStorage.length 的值是多少?

标签: javascript if-statement for-loop local-storage


【解决方案1】:

尝试更改您的 for 语句,使其显示为 i &lt; localStorage.length

循环从不执行的原因是循环中的语句必须是TRUE 才能执行。循环在此语句保持 TRUE 时执行。

您还可以在循环中删除i 的重新初始化,因为您已经有一个变量i

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多