Reputation: 1459
I have an array that is defined like so: var alpha = ['a', 'b', 'c'];
. How do I print the array which results in something like this?
a
b
c
I have my own code but it doesn't solve my problem because it prints the value of an array like this:
a,b,c
Upvotes: -1
Views: 107
Reputation: 46365
Join the elements together with a carriage return:
var alpha = ['a', 'b', 'c', 'd'];
var oneString = alpha.join('\n');
alert(oneString);
Or you could use console.log(oneString)
. You don't even need the intermediate variable - you could do
var alpha = ['a', 'b', 'c', 'd'];
console.log(alpha.join('\n'));
Nice and compact. The join()
function will concatenate the elements of the array; it will normally use the comma as separator, but you can override this with your own separator (the argument to the function). That's how this works - very compact, no iterating.
see http://jsfiddle.net/znAPK/
Upvotes: 6
Reputation: 184
The JavaScript Array global object is a constructor for arrays, which are high-level, list-like objects.
Syntax
[element0, element1, ..., elementN]
new Array(element0, element1, ..., elementN)
new Array(arrayLength)
var arr = ["this is the first element", "this is the second element"];
console.log(arr[0]); // prints "this is the first element"
console.log(arr[1]); // prints "this is the second element"
console.log(arr[arr.length - 1]); // prints "this is the second element"
Try this syntax according to your code
Upvotes: 0
Reputation: 91619
Just use the length of the array to iterate it with a for
loop:
var alpha = ['a', 'b', 'c'];
for (var i = 0; i < alpha.length; i++) {
console.log(alpha[i]);
}
Upvotes: 9