-1

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
4
  • Do you just want to print each element? alpha.forEach(function(x) { console.log(x); }) Commented Oct 16, 2013 at 3:58
  • Print it like that where? In HTML? Or the console? What for? Commented Oct 16, 2013 at 3:59
  • Do you want this output to appear on the console? Can you join the elements of the array with a "\n" "separator"? Commented Oct 16, 2013 at 3:59
  • 2
    Looks like you need to learn about loops. Commented Oct 16, 2013 at 3:59

3 Answers 3

9

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]);
}
Sign up to request clarification or add additional context in comments.

Comments

6

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/

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.