Reputation: 105
var number = prompt('Enter Number (as long as you want): '),
output = [],
sNumber = number.toString(),
lastDigit,
result,
i;
function result(number) {
for (i = 0, len = sNumber.length; i < len; i += 1) {
output.push(+sNumber.charAt(i));
}
lastDigit = output.slice(-1);
switch (lastDigit[0]) {
case 0:
return 'zero';
break;
case 1:
return 'one';
break;
.....etc some more cases.......
default: return 'not a valid number';
break;
}
}
jsConsole.writeLine('Last digit in English: ' + result);
Why the results ended with all the code but not one of the switch cases? I have struggled to get it fixed. I just want the result in the switch case to be printed.
Upvotes: 0
Views: 47
Reputation: 48415
number
parameter then use it, don't use global variablesbreak
if you have return
prompt
will return a string, so no need for toString()
on itLike this:
var sNumber = prompt('Enter Number (as long as you want): ');
function result(number) {
var output = [];
for (var i = 0; i < number.length; i ++) {
output.push(+number.charAt(i));
}
var lastDigit = output.slice(-1);
switch (lastDigit[0]) {
case 0:
return 'zero';
case 1:
return 'one';
default:
return 'not a valid number';
}
}
jsConsole.writeLine('Last digit in English: ' + result(sNumber));
For your information, you can get the last character of a string without a loop:
var lastDigit = number[number.length-1];
// assuming it will always have at least 1 character, add validation to be sure
Upvotes: 3
Reputation: 3659
You are not actually calling result.
To call result you should do:
result()
Without parentheses you are meaning the value of result which in fact is a function.
If you also concatenate it to some string, type coercion make you to end up with the same as you were did:
jsConsole.writeLine('Last digit in English: ' + result.toString());
Upvotes: 0