admin管理员组文章数量:1332394
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>
本文标签: htmlJavascript Arrays printing undefined before the array itemsStack Overflow
版权声明:本文标题:html - Javascript Arrays printing undefined before the array items - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742281941a2446254.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论