I have function in JavaScript:
function calc(num) {
if (num <= 22) {
return parseInt(num);
} else {
num += '';
var curr = 0;
for (var i = 0; i < num['length']; i++) {
curr += parseInt(num[i]);
};
return curr;
};
};
This function calculates new number like: if I have number greater than 22, this function returns new number which is a sum of it's subdigits (e.g. 28 > 22 => return (2+8) ).
This function works great in Firefox, but I'm getting "NaN" error in Internet Explorer with numbers greater than 22. So the problem must be in "else".
What's wrong?
I have function in JavaScript:
function calc(num) {
if (num <= 22) {
return parseInt(num);
} else {
num += '';
var curr = 0;
for (var i = 0; i < num['length']; i++) {
curr += parseInt(num[i]);
};
return curr;
};
};
This function calculates new number like: if I have number greater than 22, this function returns new number which is a sum of it's subdigits (e.g. 28 > 22 => return (2+8) ).
This function works great in Firefox, but I'm getting "NaN" error in Internet Explorer with numbers greater than 22. So the problem must be in "else".
What's wrong?
Share Improve this question asked Oct 25, 2011 at 16:54 xZ6a33YaYEfmvxZ6a33YaYEfmv 1,8164 gold badges25 silver badges43 bronze badges 7-
2
Please supply a decimal radix to
parseInt()
:parseInt(num[i], 10)
. It's a very bad habit to omit that second parameter. – Michael Berkowski Commented Oct 25, 2011 at 16:57 -
1
A guess: Try
num = num + '';
if+=
is not defined for string concatenation. – Hogan Commented Oct 25, 2011 at 16:57 - I've tried radix, but no effect – xZ6a33YaYEfmv Commented Oct 25, 2011 at 16:58
-
2
Try
num.charAt(i)
instead ofnum[i]
. I think IE does not implement array access for strings. – Felix Kling Commented Oct 25, 2011 at 17:00 - 3 @ieaglle - even if radix isn't the solution to this problem, you should still include it; as Michael says, it is bad practice to omit it, and it will e back to bite you one day. – Spudley Commented Oct 25, 2011 at 17:02
2 Answers
Reset to default 7You need to num.charAt(i)
as you cannot access string characters with String[offset]
in IE.
(s = "qwe"; alert(typeof s[1] === 'undefined')
is true
)
Try this:
function calc(num) {
if (num <= 22) {
return parseInt(num);
} else {
number = num.toString();
var curr = 0;
for (var i = 0; i < number.length; i++) {
curr += parseInt(number.charAt(i));
};
return curr;
};
};
alert(calc(23));
worked for me on firefox and IE