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

Several pitfalls you need to pay attention to when using the typeof operator in JavaScript_javascript tips

WBOY
Release: 2016-05-16 16:32:08
Original
1498 people have browsed it

typeof is an operator, and the result it returns to the operand is a string, there are 6 types (only for ES, not including HOST environment objects).

1.'undefined'
2.'boolean'
3.'string'
4.'number'
5.'object'
6.'function'

Because it is an operator itself, it is not a function, so there is no need to add parentheses when using it.

Copy code The code is as follows:

if (typeof(obj) === 'undefined') {
// ...
}

typeof is used to determine the type, but it has several pitfalls

1. Returning null is 'object', but you cannot really use it as an object.

Copy code The code is as follows:

var obj = null
if (typeof obj === 'object') {
Obj.a() // Error reported here
}

2. The return value for NaN is 'number', but you cannot use it for arithmetic operations.

Copy code The code is as follows:

var obj = {}
var num = parseInt(obj.a)
if (typeof num === 'number') {
num = num 10 // After execution, num is still NaN
}

3. Objects, arrays, and regular expressions cannot be distinguished, and operations on them all return 'object'.

Copy code The code is as follows:

var obj = {}
var arr = []
var reg = /pop/g
console.log(typeof obj) // 'object'
console.log(typeof arr) // 'object'
console.log(typeof reg) // 'object'

4. Safar5 and versions before Chrome7 return 'function' for regular objects.

Finally, paste the explanation in the specification

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!