Heim  >  Artikel  >  Web-Frontend  >  javascript中检测变量的类型的代码_javascript技巧

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

WBOY
WBOYOriginal
2016-05-16 18:13:16948Durchsuche

常用检查变量类型的方法有两种,下面是解说:
检查变量类型方法一: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") { ... }

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn