SoFunction
Updated on 2025-04-10

Share the singular writing method of JS to determine that elements are numbers

This is seen in reading the underscore (1.3.3) source code, its each method
Copy the codeThe code is as follows:

var each = _.each = _.forEach = function(obj, iterator, context) {
if (obj == null) return;
if (nativeForEach && === nativeForEach) {
(iterator, context);
} else if ( === +) {
for (var i = 0, l = ; i < l; i++) {
if ((context, obj[i], i, obj) === breaker) return;
}
} else {
for (var key in obj) {
if (_.has(obj, key)) {
if ((context, obj[key], key, obj) === breaker) return;
}
}
}
};

There is a sentence in this method
Copy the codeThe code is as follows:
if ( === +)

I didn't understand after reading for a long time. After being guided by an expert, this sentence is equivalent to
Copy the codeThe code is as follows:
if (typeof === 'number')

That is to determine whether an element is of numeric type. typeof and is a common way of writing. The last one is not common and difficult for ordinary people to understand.

Some libraries have tool functions for type judgment, such as
Copy the codeThe code is as follows:

function isNumber1(a){
return typeof a === 'number'
}

Or use
Copy the codeThe code is as follows:

function isNumber2(a) {
return (a) === '[object Number]'
}

Change to this writing
Copy the codeThe code is as follows:

function isNumber3(a){
return a === +a
}

Test with various types
Copy the codeThe code is as follows:

var arr = ['1', true, false, undefined, null, {}, [], 1]
for (var i=0; i<; i++) {
(isNumber3(arr[i]))
}

The result is that only the last item in the array is true. That is, only the number type a === +a is true.
Why not use typeof, because string comparison theoretically requires traversing all characters, and the performance is proportional to the length of the string.