我无法显示我已经/没有读过DOM的书籍数组
var booksListArray = [
{
title: "Always Running",
author: "Luis J Rodriguez",
alreadyRead: true
},
{
title: "Hatchet",
author: "Gary Paulsen",
alreadyRead: true
},
{
title: "Autobiography of Malcolm X",
author: "Malcolm X",
alreadyRead: true
},
{
title: "Che Guevara: A Revolutionary Life",
author: "Jon Lee Anderson",
alreadyRead: false
},
{
title: "The Prince",
author: "Niccolo Machiavelli",
alreadyRead: false
}];
for (i = 0; i < booksListArray; i++) {
var currentBook = booksListArray[1];
};
if (currentBook.alreadyRead == true) {
document.write("I have already read " + currentBook.title + " by " + currentBook.author);
} else {
document.write("You still have to read " + currentBook.title + " by " + currentBook.author);
}
答案 0 :(得分:4)
我想你想做这样的事情:
for (var i = 0; i < booksListArray.length; i++) {
var currentBook = booksListArray[i];
if (currentBook.alreadyRead == true) {
document.write("I have already read " + currentBook.title + " by " + currentBook.author);
} else {
document.write("You still have to read " + currentBook.title + " by " + currentBook.author);
}
}
您的代码有几个错误/坏处:
- 你太早关闭循环
- 循环的条件不是使用数组的length
- 您需要使用i
访问currentBook
- 使用var
或let
初始化i
变量
- 您应该填充HTML element
而不是使用document.write
以下是一个完整的工作示例:
var booksListArray = [
{
title: "Always Running",
author: "Luis J Rodriguez",
alreadyRead: true
},
{
title: "Hatchet",
author: "Gary Paulsen",
alreadyRead: true
},
{
title: "Autobiography of Malcolm X",
author: "Malcolm X",
alreadyRead: true
},
{
title: "Che Guevara: A Revolutionary Life",
author: "Jon Lee Anderson",
alreadyRead: false
},
{
title: "The Prince",
author: "Niccolo Machiavelli",
alreadyRead: false
}];
var mydiv = document.getElementById('mylist');
for (var i = 0; i < booksListArray.length; i++) {
var currentBook = booksListArray[i];
if (currentBook.alreadyRead == true) {
mydiv.innerHTML += "I have already read " + currentBook.title + " by " + currentBook.author + "<br>";
} else {
mydiv.innerHTML += "You still have to read " + currentBook.title + " by " + currentBook.author + "<br>";
}
}
&#13;
<div id="mylist"></div>
&#13;
答案 1 :(得分:2)
for (var i = 0; i < booksListArray.length; i++) {
var currentBook = booksListArray[i]; //index should be i
if (currentBook.alreadyRead === true) {
document.write("I have already read " + currentBook.title + " by " + currentBook.author);
} else {
document.write("You still have to read " + currentBook.title + " by " + currentBook.author);
}
};