JavaScript的几种检测方式

typeof 运算符

  • typeof操作符是确定一个变量是字符串、数值、布尔值、还是undefined的最佳工具。但是如果变量是一个对象或者null,typeof就会只返回一个“Object”。
  • 栗子
    var str = "javascript";
    var bool = true;
    var num = 22;
    var nan = NaN;
    var und;
    var nu = null;
    var obj = new Object();
    console.log(typeof str); //string
    console.log(typeof bool); //boolen
    console.log(typeof num); //number
    console.log(typeof nan); //number
    console.log(typeof und);//undefined
    console.log(typeof nu);//Object
    console.log(typeof obj);//object
  • NaN:是Number的一个特殊的值,因此typeof NaN也是number。
  • 关于typeof的注意点
  • typeof [变量名] ---》值为"变量对应的类型",注意外面要有引号。
  • typeof(typeof([要检测的数据])) 不管嵌套几层typeof,值都是"string"。

instanceof 操作符 检测一个对象是否是另一个对象的实例

  • instanceof用法
obj instabceof Object;
person1 instanceof Object
person1 instanceof Person
复制代码

在检测一个引用类型值和Object构造函数时,instanceof始终会返回true,当然,如果当用instanceof检测基本类型时,则返回false。

hasOwnProperty

  • hasOwnProperty 只在属性存在于实例中才返回true
function Persin(){}
Person.prototype.name = "rm";
var person1 = new Person();

console.log(person1.hasOwnProperty("name"));//false

person1.name = "red";
cosnole.log(person1.name);//red
console.log(person1.hasOwnProperty("name"));//true;
复制代码

isPrototypeOf()

  • 用来判断其原型链的对象是否存在于指定对象实例中,是则返回true,否则返回false

toString()

  • 严格检查数据类型
Object.prototype.toString.call("str");//"[object String]"
Object.prototype.toString.call(22);//"[object Number]"
Object.prototype.toString.call(true);//"[object Boolean]"
Object.prototype.toString.call([3,5]);//"[object Array]"
Object.prototype.toString.call({a:2});//"[object Object]"
Object.prototype.toString.call(undefined);//"[object Undefined]"
Object.prototype.toString.call(null);//"[object Null]"
···
复制代码

in

  • 有2种方式使用,一种用来for-in循环中使用,在单独使用使,in操作符会在通过对象能够访问给定属性时返回true,无论改属性存在于实例还是原型中。
function Persin(){}
Person.prototype.name = "rm";
Person.protptype.age = 18;
Person.prototype.job = "lll";
Person.prototype.setName = function(){
    console.log(this.name);
}
var person1 = new Person();
var person2 = new Person();

console.log(person1.hasOwnProperty("name"));//false
console.log("name" in person1);//true,来自原型

person1.name = "red";
cosnole.log(person1.name);//red,来自实例
console.log(person1.hasOwnProperty("name"));//true;
console.log("name" in person1); //true

console.log(person2.name); //rm,来自原型
console.log(person2.hasOwnProperty("name");//false
console.log("name" in person2);//true
复制代码
  • 同时使用hasOwnProperty和in可以准确知道该属性是存在于实例中还是存在于原型中
function hasPrototypeProperty(obj,name){
    return !object.hasOwnProperty(name) && (name in object)
}
复制代码
  • 检查公有属性
function checkPublicAttribute(obj,attr){
    return (attr in obj) && obj.hasOwnProperty(attr)
}

复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值