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.
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.
Share Improve this question edited Jan 7, 2015 at 14:07 Korvo 9,7529 gold badges59 silver badges128 bronze badges asked Jan 7, 2015 at 13:58 Mathew Gregory HarrisonMathew Gregory Harrison 711 silver badge7 bronze badges 1- To allow people to easily help you, consider making a jsfiddle of your problem. jsfiddle is a site where you can run javascript with html live in the browser. – Relequestual Commented Jan 7, 2015 at 14:04
3 Answers
Reset to default 7It'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(" ");
More info: http://www.w3schools./jsref/jsref_join.asp
In code ,you have just declared,not initialized.so,just replace
var arrayString;
with
var arrayString = '';
Hope it helps...Thank you.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744370636a4570931.html
评论列表(0条)