I can't find a way to make a list with words instead of numbers. For example:
for(var i = 0; i < 10; i++) {
console.log(i + '');
}
in this code it will give all the numbers from 0
to 9
.
And if I want to put the words how to do it?
I can't find a way to make a list with words instead of numbers. For example:
for(var i = 0; i < 10; i++) {
console.log(i + '');
}
in this code it will give all the numbers from 0
to 9
.
And if I want to put the words how to do it?
There are a lot of ways to accomplish this task.
One way is by storing the numbers in an array and then just outputting the number at each index of the array:
let numbers = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine'];
for(var i = 0; i < 10; i++) {
console.log(`${i} ${numbers[i]}`);
}
You could also use if
statements or a switch
statement (shown below):
for(var i = 0; i < 10; i++) {
var output = i + ' ';
switch (i) {
case 0:
output += 'Zero';
break;
case 1:
output += 'One';
break;
case 2:
output += 'Two';
break;
default:
output += 'And so on...';
break;
}
console.log(output);
}
If may be better to clarify the exact need in your case as this example will clearly only work for numbers between 0 and 9.
Here is a post with some clever answers that provide for many more numbers as words: JavaScript numbers to Words