我很难在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);
}发布于 2017-06-22 18:13:53
我觉得你想做这样的事:
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访问您的currentBookvar或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>";
}
}<div id="mylist"></div>
发布于 2017-06-22 18:19:17
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);
}
};https://stackoverflow.com/questions/44706619
复制相似问题