对于以下代码段:
<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
我需要更改代码才能获得预期的输出。这种输出的原因是什么?
答案 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