Only just started learning JavaScript.
Why won't my button display the values in my "authors" array?
/* 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>
Sorry for the terrible formatting, I'm new here. I'm probably missing something super basic..
As someone else already said, you weren't passing in authors, and since you had a parameter named authors
it wouldn't use authors defined in your js file.
Also, when you iterate through your loop, you should not do <= to length
, as arrays are zero index.
Finally, your code would be formatted more cleanly if you use authors.join(', ')
to write instead of looping through the values without adding any additional formatting.
/* 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>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments