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

Sharing the strange way of writing JS to determine whether an element is a number

黄舟
Release: 2016-12-12 11:37:22
Original
1154 people have browsed it

Its each method

代码如下:
var each = _.each = _.forEach = function(obj, iterator, context) { 
if (obj == null) return; 
if (nativeForEach && obj.forEach === nativeForEach) { 
obj.forEach(iterator, context); 
} else if (obj.length === +obj.length) { 
for (var i = 0, l = obj.length; i < l; i++) { 
if (iterator.call(context, obj[i], i, obj) === breaker) return; 
} 
} else { 
for (var key in obj) { 
if (_.has(obj, key)) { 
if (iterator.call(context, obj[key], key, obj) === breaker) return; 
} 
} 
} 
};
Copy after login

There is a sentence in this method

if (obj.length === +obj.length)
Copy after login

This sentence is equivalent to

if (typeof obj.length === &#39;number&#39;)
Copy after login

, which is used to determine whether the element is of numeric type. typeof and Object.prototype.toString are common ways of writing. The last one is uncommon and difficult for ordinary people to understand.

Some libraries have tool functions for type judgment, such as

代码如下:
function isNumber1(a){ 
return typeof a === &#39;number&#39; 
}
Copy after login

or you can use Object.prototype.toString

代码如下:
function isNumber2(a) { 
return Object.prototype.toString.call(a) === &#39;[object Number]&#39; 
}
Copy after login

to change it to this way of writing

代码如下:
function isNumber3(a){ 
return a === +a 
}
Copy after login

Use various types to test

代码如下:
var arr = [&#39;1&#39;, true, false, undefined, null, {}, [], 1] 
for (var i=0; i<arr.length; i++) { 
console.log(isNumber3(arr[i])) 
}
Copy after login

The result is only the last one of the array item is true. That is, only the numeric type a === +a is true.
Why not use typeof? Because string comparison theoretically needs to traverse all characters, and the performance is directly proportional to the length of the string.

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!