I keep getting undefined before my output text in JS. Here is my code.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Learning javascript</title>
</head>
<body>
<p id="arrayString"></p>
<!-- Javascript -->
<script type="text/javascript" src="JS/app2.js"></script>
</body>
</html>
This is my JS
var arrayString;
var myArray=["Ms.Vickies", "Old Dutch", "Lays"];
for (var i=0; i<myArray.length; i++) {
arrayString=arrayString+myArray[i];
}
document.getElementById("arrayString").innerHTML=arrayString;
my output is undefinedMs.VickiesOld DutchLays
In addition why no spaces? I am new to JS but am working my way up. Cannot figure this out.
It's because in your first loop iteration, arrayString
is undefined. Set it equal to an empty string instead.
Instead of declaring arrayString
like so:
var arrayString;
Initialize it with an empty string:
var arrayString = '';
Because you are initiating a null/undefined variable by doing this: var arrayString;
You can fix it by doing this: var arrayString = "";
Better yet, instead of using a for
loop, you can do it like this:
var myArray=["Ms.Vickies", "Old Dutch", "Lays"];
document.getElementById("arrayString").innerHTML = myArray.join(" ");
In code ,you have just declared,not initialized.so,just replace
var arrayString;
with
var arrayString = '';
Hope it helps...Thank you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.