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

javascript中检测变量的类型的代码_javascript技巧

WBOY
Release: 2016-05-16 18:13:16
Original
952 people have browsed it

常用检查变量类型的方法有两种,下面是解说:
检查变量类型方法一:typeof
格式:typeof 变量
用法:if( typeof 变量 == "类型标识") { ... }
下面是一些常用数据类型对应的typeof值:
{an:"object"}      :    object
["an","array"]      :    object
function() {}      :    function
"a string"        :    string
55           :    number
true          :    boolean
new User()      :    object

从上表中,可以看出用typeof取得变量类型时,对于数组、对象、自定义类的对象同视为object,其它类型检查正常。所以它无法判断出对象是object,还是array,还是User。那么,此时我们可用第二种方法处理。

检查变量类型方法二:构造函数法(constructor)
格式:变量.constructor
用法:if(变量.constructor == "类型标识符") { ... }
{an:"object"}      :    Object
["an","array"]      :    Array
function() {}      :    Function
"a string"        :    String
55           :    Number
true          :    Boolean
new User()      :    User

从上表中可以看出,我们能正确获取到每种数据的类型。所以,尽量使用变量的构造函数来获取变量类型更好。
不过,有时候这样也更方便:
if(typeof 变量 == "undefined") { ... }

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!