admin管理员组文章数量:1327744
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
本文标签: internet explorerJavaScript parseInt IE Nan errorStack Overflow
版权声明:本文标题:internet explorer - JavaScript parseInt IE Nan error - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742230151a2437074.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论