简体   繁体   中英

Fastest way to check if a JS variable starts with a number

I am using an object as a hash table and I have stuffed both regular properties and integers as keys into it.

I am now interested in counting the number of keys in this object which are numbers, though obviously a for (x in obj) { if (typeof x === "number") { ... } } will not produce the result I want because all keys are strings.

Therefore I determined that it is sufficient for my purposes to assume that if a key's first character is a number then it must be a number so I am not concerned if key "3a" is "wrongly" determined to be a number.

Given this relaxation I think i can just check it like this

for (x in obj) {
  var charCode = x.charCodeAt(0);
  if (charCode < 58 && charCode > 47) { // ascii digits check
     ...
  }
}

thereby avoiding a regex and parseInt and such.

Will this work? charCodeAt is JS 1.2 so this should be bullet-proof, yes?

Hint: I would love to see a jsperf comparing my function with what everyone comes up with. :) I'd do it myself but jsperf confuses me

Update: Thanks for starting up the JSPerf, it confirms my hope that the charCodeAt function would be executing a very quick piece of code reading out the int value of a character. The other approaches involve parsing.

parseInt(x, 10) will correctly parse a leading positive or negative number from a string, so try this:

function startsWithNumber(x) {
    return !isNaN(parseInt(x, 10));
}

startsWithNumber('123abc'); // true
startsWithNumber('-123abc'); // true
startsWithNumber('123'); // true
startsWithNumber('-123'); // true
startsWithNumber(123); // true
startsWithNumber(-123); // true
startsWithNumber('abc'); // false
startsWithNumber('-abc'); // false
startsWithNumber('abc123'); // false
startsWithNumber('-abc123'); // false

The question is misleading because it is hard to tell this of a variable 's name but in the example you're dealing with object properties (which are some kind of variables of course...). In this case, if you only need to know if it starts with a number, probably the best choice is parseInt . It will return NaN for any string that doesn't start with a number.

Why speculate when you can measure . On Chrome, your method appears to be the fastest. The proposed alternatives all come at about 60% behind on my test runs.

您也可以使用isNaN(x)isFinite(x) -看到这个问题

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM