jQuery's change of isNumeric (in latest versions)?

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?

Answers:

Answer

The 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).

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.