Until recent version , jQuery used to check if numeric via :
return !isNaN( parseFloat(obj) ) && isFinite( obj );
The first part is for :
parseFloat("d") //Nan
!isNaN( parseFloat(Infinity)) //true but not a number
The second part is for :
isFinite('2') //true
But in recent version they changed it and changed it to :
return !jQuery.isArray(obj) && (obj - parseFloat(obj) + 1) >= 0;
Question:
What was not good enough in the previous version that they changed it to the new one ? And why do they check if array?
Until recent version , jQuery used to check if numeric via :
return !isNaN( parseFloat(obj) ) && isFinite( obj );
The first part is for :
parseFloat("d") //Nan
!isNaN( parseFloat(Infinity)) //true but not a number
The second part is for :
isFinite('2') //true
But in recent version they changed it and changed it to :
return !jQuery.isArray(obj) && (obj - parseFloat(obj) + 1) >= 0;
Question:
What was not good enough in the previous version that they changed it to the new one ? And why do they check if array?
Share Improve this question edited Jun 22, 2015 at 13:10 Royi Namir asked Jun 22, 2015 at 12:27 Royi NamirRoyi Namir 149k144 gold badges491 silver badges829 bronze badges 4 |2 Answers
Reset to default 16The same value of obj
answers both your questions : [3]
!isNaN( parseFloat(obj) ) && isFinite( obj )
is true
for [3]
.
(obj - parseFloat(obj) + 1) >= 0
is true
for [3]
.
The reason behind those problems is that a conversion to string or number occurs in parseFloat
and in isFinite
and that the conversion to string of an array is the result of joining with commas the conversion of its elements to strings.
So this change is a bug fix.
Note that you can still make it "fail" with values like {toString:function(){ return 3}}
but it's unclear what jQuery should really return in such a case (this object really wants to appear as a number, after all).
The previous version, for example, didn't correctly work for arrays that had a single numeric element:
var obj = [1];
(!isNaN( parseFloat(obj) ) && isFinite(obj)); //true
var obj = [1, 2];
(!isNaN( parseFloat(obj) ) && isFinite(obj)); //false
&&
will be omitted. – Justinas Commented Jun 22, 2015 at 12:31