0

I don't have any experience with javascript and I have a basic question about arrays. I can't seem to find it on the internet.

I'm using a basic array like this:

var names = new Array('Jorn', 'Janine', 'Peter', 'Magchiel', 'Marieke', 'Pieter');

The output needs to be something like this:

[0] = Jorn, [1] = Janine, [2] = Peter, ...

And so on. I'm really struggling with this.

I hope someone could help me with this.

Thanks in advance!

2 Answers2

1

This basically builds a string for output via a for-loop, then tells the windows to output the raw string.

var output="";
for(var i=0;i<names.length;i++){
output+="[" + i + "]" + " = " + names[i] + ", ";
}
output=output.slice(0,-2);
document.write(output);
em_
  • 2,134
  • 2
  • 24
  • 39
  • 1
    use `str.slice(0,-1);` to remove last char, [not substring with negative values](http://stackoverflow.com/questions/6918943/substr-with-negative-value-not-working-in-ie), but I think you want the last 2 chars (not only 1). On a side note, I do use substring to remove first char like `str.substring(1);` – ajax333221 Oct 23 '13 at 14:40
  • actually, my mistake, you weren't using negative values, but anyway, the new way is shorter and works one IE6+ – ajax333221 Oct 23 '13 at 14:46
  • I usually use slice, not sure why I originally went w/ substring :S – em_ Oct 23 '13 at 14:49
-1

That should work, iterate over keys "foreach-like" and get their values :

var names = new Array('Jorn', 'Janine', 'Peter', 'Magchiel', 'Marieke', 'Pieter');
var result = '';
for(var i in names){
    result += '[' + i + '] = ' + names[i] + ', ';
}
alert(result);
Florian F.
  • 4,700
  • 26
  • 50
  • Thanks alot! This worked, I knew it was something with a foreach but I didn't know how to use it. – user2911779 Oct 23 '13 at 14:40
  • 2
    Actually that's a bad solution. Using `for .. in` with arrays is wrong. Use a proper `for` loop like in ElliotM's answer. – Tomalak Oct 23 '13 at 14:42
  • It's a bad idea only if you rewrite array prototype, and even then you can use something like `names.hasOwnProperty(i)` to make sure it's an actual array element. Or did you think of something else ? – Florian F. Oct 23 '13 at 14:45