gpt4 book ai didi

javascript - 基本显示数组值?

转载 作者:行者123 更新时间:2023-11-29 23:28:24 24 4
gpt4 key购买 nike

才刚刚开始学习 JavaScript。

为什么我的按钮不显示“作者”数组中的值?

/* JavaScript file */
var authors = ['Ernest Hemingway', 'Charlotte Bronte',
'Dante Alighieri', 'Emily Dickinson'
];

function ShowAuthors(authors) {
for (i = 0; i <= authors.length; i++) {
document.write(authors[i]);
}
}
<!DOCTYPE html>
<html>

<head>
<title></title>
<script src="./js/script.js"></script>
<link rel="stylesheet" href="./css/style.css" />
</head>

<body>
<div class="container">
<input type="button" class="author" value="Show Authors" onClick="ShowAuthors()" />
</div><br>
</body>

</html>

抱歉格式太糟糕了,我是新来的。我可能遗漏了一些非常基本的东西..

最佳答案

正如其他人所说,您没有传递作者,并且由于您有一个名为 authors 的参数,它不会使用您的 js 文件中定义的作者。

此外,当您遍历循环时,您不应该对 length 执行 <=,因为数组是零索引。

最后,如果您使用 authors.join(', ') 来编写而不是在不添加任何额外格式的情况下循环遍历值,您的代码将被格式化得更干净。

/* JavaScript file */
var authors = ['Ernest Hemingway', 'Charlotte Bronte',
'Dante Alighieri', 'Emily Dickinson'
];

function ShowAuthors() {
document.write(authors.join(', '))
}
<!DOCTYPE html>
<html>

<head>
<title></title>
<script src="./js/script.js"></script>
<link rel="stylesheet" href="./css/style.css" />
</head>

<body>
<div class="container">
<input type="button" class="author" value="Show Authors" onClick="ShowAuthors()" />
</div><br>
</body>

</html>

关于javascript - 基本显示数组值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48212803/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com