I am having trouble printing a simple array list in javascript. undefined is being printed before only two array items. please consider the code below;
function buildList(){
var box = document.getElementById("box");
var startList = "<ol>";
var endList = "</ol>";
var listItems;
var arry = ["Go to shopping", "Go to Mall"];
for(var i = 0; i < arry.length; i++){
listItems += "<li>" + arry[i] + "</li>";
}
box.innerHTML = startList + listItems + endList;
}
document.onLoad(buildList());``
<div id="box">
</div>
I am having trouble printing a simple array list in javascript. undefined is being printed before only two array items. please consider the code below;
function buildList(){
var box = document.getElementById("box");
var startList = "<ol>";
var endList = "</ol>";
var listItems;
var arry = ["Go to shopping", "Go to Mall"];
for(var i = 0; i < arry.length; i++){
listItems += "<li>" + arry[i] + "</li>";
}
box.innerHTML = startList + listItems + endList;
}
document.onLoad(buildList());``
<div id="box">
</div>
output of this is
undefined 1) Go to shopping 2) Go to Mall
Please help.
Share Improve this question edited Aug 14, 2015 at 20:39 Sarath Chandra 1,88620 silver badges40 bronze badges asked Aug 14, 2015 at 20:26 J AkhtarJ Akhtar 6671 gold badge9 silver badges27 bronze badges 2-
You forgot to initialize
listItems
– Pointy Commented Aug 14, 2015 at 20:29 - Hi @knight, if any answer has solved your question please consider accepting it by clicking the check-mark. This indicates to the wider munity that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this. – Sarath Chandra Commented May 6, 2016 at 11:32
4 Answers
Reset to default 6Your listItem
variable is undefined because it is not initialized.
var listItems = "" ;
(at line 5) should solve your problem.
You are declaring var listItems;
=> undefined, you should do as follows: var listItems = "";
=> declared and initialized as an empty string.
You have to initialize listItems.
var listItems = "";
What you are doing right now is adding a string to listItems, but you did not define listItems. It does not know what is listItem
Try this.
In your code you missing var listItems=""
;
Here is full code
function buildList()
{
var box = document.getElementById("box");
var startList = "<ol>";
var endList = "</ol>";
var listItems="";
var arry = ["Go to shopping", "Go to Mall"];
for(var i = 0; i < arry.length; i++)
{
listItems += "<li>" + arry[i] + "</li>";
}
box.innerHTML = startList + listItems + endList;
}
document.onLoad(buildList());``
<div id="box">
</div>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742281941a4414649.html
评论列表(0条)