Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 745
Royi Namir Avatar asked Jun 22 '15 12:06

Royi Namir


2 Answers

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

like image 180
Denys Séguret Avatar answered Oct 18 '22 08:10

Denys Séguret


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
like image 35
Etheryte Avatar answered Oct 18 '22 08:10

Etheryte