为什么脚本会产生意外的输出

时间:2014-08-13 08:42:35

标签: javascript html

对于以下代码段:

<body>
<p id="demo"></p>
<script>
cars = ("BMW", "Volvo", "Saab", "Ford","Ranjith");
text="";
for(i=0;i<cars.length;i++)
{
 text+=cars[i] +"<br/>"
}
document.getElementById("demo").innerHTML = text;
</script>
</body>

输出为:

R
a
n
j
i
t
h

预期产出为:

BMW
Volvo
Saab
Ford
Ranjith

我需要更改代码才能获得预期的输出。这种输出的原因是什么?

2 个答案:

答案 0 :(得分:4)

cars不是数组,请使用[]标记数组变量。试试这个:

<body>
<p id="demo"></p>
<script>
var cars = ["BMW", "Volvo", "Saab", "Ford","Ranjith"];
var text="";
for(i=0;i<cars.length;i++){
    text+=cars[i] +"<br/>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>

答案 1 :(得分:0)

var cars = new Array(10); // this will create  a 10 item long array with all slots containing undefined

var cars = [];

阅读Array