JavaScript中如何检测一个变量是一个String类型?

1 typeof x === "string"
2 typeof(x) === "string'    // 小写
3 x.constructor === String     // 大写类型

同理:Number, Boolean Function 类型也可以这样检测

注意:object不同

var obj = {
        'age':19,
        'put':function(){
                return 0;
        }
}

这样定义的对象与前面规则一样

 var Obj = function(){
                this.age = 12;
                this.put = function(){
                        return 0;
                }
        }

var obj = new Obj;
        typeof obj = "object"

通过构造函数构建对象,obj.constructor = ƒ Function() { [native code] }      typeof obj = "object"

所以Object类型检测要注意构造方法。

转载于:https://www.cnblogs.com/tzdy/p/10792165.html

你可能感兴趣的:(javascript)