Several pitfall _ JavaScript tips for using the typeof operator in javascript

Source: Internet
Author: User
This article mainly introduces several pitfalls that need to be paid attention to when using the typeof operator in JavaScript. This article summarizes four issues that need attention when using the typeof operator. If you need a friend, refer to typeof as an operator, it returns a string of 6 types (only for ES and does not contain the HOST environment object ).

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

Because it is an operator, it is not a function, and there is no need to add parentheses during use.

The Code is as follows:


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

Typeof is used to determine the type. It has several pitfalls.

1. the return value for null is 'object', but you cannot actually use it as an object.

The Code is as follows:


Var obj = null
If (typeof obj = 'object '){
Obj. a () // an error is reported here.
}

2. NaN returns 'number', but you cannot use it for arithmetic operations.

The Code is as follows:


Var obj = {}
Var num = parseInt (obj.)
If (typeof num = 'number '){
Num = num + 10 // after execution, num is still NaN
}

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

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. In versions 5 and earlier than Chrome7, 'function' is returned for the regular object '.

Finally, paste the explanation in the Specification

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.