1

I have this code using javascript :

var arr = [
  'one',
  'two',
  'three',
  'four',
  'five'
];


for (var property1 in arr) {
  console.log(property1);
}

And when I execute this code I get :

'1'
'2'
'3'
'4' 

But I would like to have this :

'one',
'two',
'three',
'four',
'five'

How can I do this using a loop for ?

Thank you very much !

Eddie
  • 26,593
  • 6
  • 36
  • 58
Jack Peter
  • 13
  • 3
  • 1
    use `for..of` like so: `for(var property1 of arr) {` - [it's bettter not to use `for..in` on arrays!](https://stackoverflow.com/a/9329476/5648954) – Nick Parsons Apr 26 '19 at 13:34
  • Thank you it is strange because in Python I will get the same result with a for..in ! – Jack Peter Apr 26 '19 at 13:40

2 Answers2

2

Use for..of like following

var arr = [
'one',
'two',
'three',
'four',
'five'
];


for(var property1 of arr) {
  console.log(property1);
}
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
1

Welcome to SO!

If you want to loop through the array then you will need to use something besides for..in. You can use for..of or a for loop but it might be good to understand why this is happening.

for..in loops through the key/value pairs of an object. The variable in the parens gets set to the key of that key/value pair. In the case of the array, It will get set to the index or any enumerable property on the array. Thats why it prints numbers instead of words.

I'd also like to point out some iteration methods that might be useful outside of imperative loops.

arr.forEach will allow you to loop through an array without needing the extra for syntax.

arr.forEach(item => console.log(item))

Other methods like arr.map and arr.filter will give you even more power as you begin to iterate through your list more.

const numbers = [1,22,11,18,16];
const add = a => b => a + b;
const isEven = number => number %2 === 0;

const biggerEvenNumbers = numbers
  .map(add(1))
  .filter(isEven) // [2,12]
ktilcu
  • 3,032
  • 1
  • 17
  • 15