javascript - 只有三个中的两个导致循环显示数组元素
问题描述
我似乎无法弄清楚为什么我不断获得第一排和第三排。由于某种原因,我跳过了第二名。这是我的代码
//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
推荐阅读
- php - Echo 检查值是否为 1
- php - PHP、PDO、表单、更新用户类未按预期工作
- java - 从 EditText 获取字符串而不会出现可为空的错误
- hdfs - Accumulo Tracer 在启动时挂起
- navigation - DNN 导航菜单链接未向客人显示
- python - Scrapy 获得的 HTML 与浏览器显示的源 HTML 完全不同
- solr - SolrCore 初始化失败错误加载类 'solr.IntField'
- php - Symfony Doctrine 执行 leftJoin 并获得所有结果
- python - 使用 pd.concat 时添加标识原始数据框的列
- enterprise-architect - 在 Sparx EA 中为刻板印象使用自定义图标集