最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery's change of isNumeric (in latest versions)? - Stack Overflow

programmeradmin2浏览0评论

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
  • For speed and drop some possible errors I think. If obj is array, than everything after && will be omitted. – Justinas Commented Jun 22, 2015 at 12:31
  • 2 See github.com/jquery/jquery/commit/… - bugs.jquery.com/ticket/15100 – Arun P Johny Commented Jun 22, 2015 at 12:38
  • 1 also bugs.jquery.com/ticket/14313 – Arun P Johny Commented Jun 22, 2015 at 12:40
  • 1 I think using the github.com/jquery/jquery history will give you a better picture on why and how those changes come in – Arun P Johny Commented Jun 22, 2015 at 12:42
Add a comment  | 

2 Answers 2

Reset to default 16

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

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
发布评论

评论列表(0)

  1. 暂无评论