-1

javascript beginner. "The for...in" question.

Applied to an array object, but days cannot be defined.

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Loops and Control</title>
</head>

<body>
<script>
  var days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
  var message = "";
  for (i in days) {
  message += 'Day ' + i + ' is' 
  day[i] + '\n';
  }
 alert(message);
 </script>
</body>
</html>
Mimose
  • 9
  • 3

4 Answers4

1

You should use for loop to iterate through Arrays. For in is not recommended for Arrays.

Otherwise you can also use forEach

var days = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
var message = [];

for(var i = 0; i < days.length; i++) {
   message.push('Day', (i + 1), 'is', days[i] + '\n');
}

alert(message.join(' '));
brightDot
  • 329
  • 2
  • 11
1

Several problems there:

  1. You've tried to use day[i], but you have no day variable (it's called days).
  2. for-in isn't meant for looping through array entries; details of your various options here.
  3. You're missing a + after ' is'
  4. Your code is falling prey to The Horror of Implicit Globals (that's a post on my anemic little blog) — you need to declare i.

So:

var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var message = "";
for (var i = 0; i < days.length; ++i) {
  message += 'Day ' + i + ' is ' + days[i] + '\n';
}
alert(message);

Alternately, array have several features that you can use to do operations on their entries. There's forEach, which loops through the entries:

var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var message = "";
days.forEach(function(day, i) {
  message += 'Day ' + i + ' is ' + days[i] + '\n';
});
alert(message);

...or reduce, which is meant for exactly this use case: Building up a result from the array's entries:

var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var message = days.reduce(function(m, day, i) {
  return m + 'Day ' + i + ' is ' + days[i] + '\n';
}, "");
alert(message);
Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

The name of the array is misspelled inside the for. It should be:

for (i in days) {
    message += 'Day ' + i + ' is' + days[i] + '\n';
}

i will take the value of the index, and you use it to access the original array

J. Maria
  • 362
  • 3
  • 14
0

You could achieve this with reduce method of the array

const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const newLine = (acc, curr) => acc += curr + '\n';
const message = days.reduce(newLine, '');
console.log(message)
mplungjan
  • 169,008
  • 28
  • 173
  • 236
user93
  • 1,866
  • 5
  • 26
  • 45