我似乎无法弄清楚为什么我一直排在第 1 和第 3 排。由于某种原因,我正在跳过第二名。这是我的代码
//define books and authors
var books = [
{ title: "Data Structures and Algorithm Analysis in C++",
publisher: "Pearson",
authors: [
{firstName: "Mark", lastName: "Weiss" }]
},
{ title: "Foundations of Finance",
publisher: "Pearson",
authors: [
{firstName: "Arthur", lastName: "Keown" },
{firstName: "John", lastName: "Martin" }]
},
{ title: "Literature for Composition",
publisher: "Longman",
authors: [
{firstName: "Sylvan", lastName: "Barnet" },
{firstName: "William", lastName: "Cain" },
{firstName: "William", lastName: "Burto" }]
}
];
function outputBooks() {
for (i=0; i<books.length; i++) {
document.write("<h2>" + books[i].title + "</h2>");
document.write("<strong>" + books[i].publisher + "</strong>"+ "<br>" + "<br>");
outputAuthors(books[i]);
}
function outputAuthors(book) {
for (i=0; i<book.authors.length; i++) {
document.write("Author's Name: ");
document.write(book.authors[i].firstName + ' ' + book.authors[i].lastName + "<br>");
}
}
}
outputBooks();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="container">
<script type="text/javascript" language="javascript" src="ass1_q1.js">
</script>
</div>
</body>
</html>
我正在尝试编写一个 JS 代码来显示带有作者姓名的三本书的书名。有什么我想念的吗?
我相信问题在于您正在全局定义i
,因此 outputAuthors 正在更改 outputBooks 的索引。这可以通过更改两个 for 循环中的代码轻松解决,for (let i = 0 ...
以便每个范围都有自己的变量i
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句