Home > Web Front-end > JS Tutorial > body text

4 methods and efficiency comparison of JavaScript to determine whether it is a number_javascript skills

WBOY
Release: 2016-05-16 16:06:37
Original
1056 people have browsed it

Today I did an efficiency comparison on Chrome for different numerical determination methods. The results are as follows:

Note: Regular expressions can only be used to determine whether the content in a string is a pure numeric value, but cannot be used to determine whether it is a numeric object. Put here only for comparison.

The code is as follows:

 var ret;
 var o = 1;
 var pattern = /^(-?\d*.?\d*)$/;
 var toStr = {}.toString;
 var array = {};
 array["[object Number]"] = "number";
 
 console.log("各种判断是否数值的速度比较!")
 
 console.log("方法一:pattern.test(o)");
 console.time("first");
 for (var i=0;i<10000;i++){
  ret = pattern.test(o);
 }
 console.timeEnd("first");
 console.log(ret);

 console.log("方法二:o instanceof Number");
 console.time("second");
 for (var i=0;i<10000;i++){
  ret = o instanceof Number;
 }
 console.timeEnd("second");
 console.log(ret);
 
 console.log("方法三:o.constructor == Number");
 console.time("thirth");
 for (var i=0;i<10000;i++){
  ret = o.constructor == Array;
 }
 console.timeEnd("thirth");
 console.log(ret);

 console.log("方法四:array[toStr.call(o)] == 'number'");
 console.time("forth");
 for (var i=0;i<10000;i++){
  ret = array[toStr.call(o)] == "number";
 }
 console.timeEnd("forth");
 console.log(ret);
Copy after login

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template