注意:通過正則表達式僅能用於字符串中的內容是否是純數值,而不能用於判斷是否是數值對象。放在此處僅用於對比。
其代碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 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);