开发者

isFinite returns true when variable is undefined

开发者 https://www.devze.com 2023-02-02 16:57 出处:网络
I\'m using isFinite to determine if a key from an array is correct, for (x in selectList) { if (isFinite(x)开发者_StackOverflow中文版) {

I'm using isFinite to determine if a key from an array is correct,

for (x in selectList) {
        if (isFinite(x)开发者_StackOverflow中文版) {
             $('#' + selectList[x])[0].selectedIndex = 0;
        }
}

I thought this was working correctly but now in Firefox isFinite is returning TRUE when x is undefined. This doesn't seem right to me. Is this a bug?


You should NEVER use for..in for arrays. There are number of things that could go wrong. See this and this for explanation.

Just use a plain vanilla for loop. You don't need to use isFinite or isNaN then.


var d;
alert(isFinite(d));

This returns false for me using the firebug console. (d is undefined since nothing has been assigned to it).

should you not be doing:

for (x in selectList) {
        if (isFinite(selectList[x])) { //x will always be defined since you are iterating through property names not the values
             $('#' + selectList[x])[0].selectedIndex = 0;
        }
}


Yes, that would be a bug. See ECMA 262. isFinite(x) should return false if toNumber(x) returns NaN (page 105) and toNumber(x) returns NaN if x is undefined (page 43).


If selectList is ordinary array, just have ordinary plain loop:

for (var x = 0; x < selectList.length; x++) {
    $('#' + selectList[x])[0].selectedIndex = 0;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号