为什么我的 'for' 语句没有循环,里面的 if 语句没有执行?
Why doesn't my 'for' statement loop and the if statement inside it execute?
我有一个函数,它有一个重复的 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;
}
尝试更改您的 for 语句,使其显示 i < localStorage.length
。
你的循环从不执行的原因是循环中的语句必须是 TRUE
才能执行。当此语句保持 TRUE
.
时循环执行
您还可以在循环中删除 i
的重新初始化,因为您已经有一个变量 i
.
我有一个函数,它有一个重复的 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;
}
尝试更改您的 for 语句,使其显示 i < localStorage.length
。
你的循环从不执行的原因是循环中的语句必须是 TRUE
才能执行。当此语句保持 TRUE
.
您还可以在循环中删除 i
的重新初始化,因为您已经有一个变量 i
.