0

For the following snippet:

<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>

Got the output as :

R
a
n
j
i
t
h

The expected output was:

BMW
Volvo
Saab
Ford
Ranjith

What do I need change in my code to get the expected output. what is the reason for such output?

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
Venkatvasan
  • 491
  • 3
  • 13
  • `cars` is not an array. The comma operator is left-associative and returns the RHS of its expression, thus the value of `cars` is the string `"Ranjith"`. Use square-brackets to make it an array: `cars=[values]` – blgt Aug 13 '14 at 08:43
  • @ blgt: thanks for the correct explanation – Venkatvasan Aug 13 '14 at 08:49
  • read this http://stackoverflow.com/questions/931872/what-s-the-difference-between-array-and-while-declaring-a-javascript-ar – Gildas.Tambo Aug 13 '14 at 08:53

2 Answers2

4

cars is not an array, please use [] to mark array variables. Try this:

<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>
nfechner
  • 17,295
  • 7
  • 45
  • 64
Girish
  • 11,907
  • 3
  • 34
  • 51
0
var cars = new Array(10); // this will create  a 10 item long array with all slots containing undefined

or

var cars = [];

read Array

Gildas.Tambo
  • 22,173
  • 7
  • 50
  • 78