检测原始值用typeof

javascript有五种原始类型,分别为字符串、数字、布尔值、null和undefined
判断一个值是什么类型的字符串,可以通过typeof
typeof variable

//检测字符串if(typeof name == “string”){
    anotherName = name.substring(3);}

检测引用值(对象)用instanceof

javascript中除了原始值之外的值都是引用,有这样几种内置的引用类型: Object Array Date 和Error,使用typeof判断所有引用类型时都返回object
检测某个引用类型值得最好方法是使用instanceof运算符
value instanceof constructor

//检测日期if(value instanceof Date){
    console.log(value.getFullYear());}

检测函数最好的方法是用typeof

检测函数用typeof,因为它可以跨帧(frame)使用,从技术的角度来说,javascript中

网友评论