typeof()介绍
typeof() 是一个一元运算,放在一个运算数之前,运算数可以是任意类型。
它返回值是一个字符串,该字符串说明运算数的类型。
typeof( )返回的值
typeof一般只能返回如下几个结果:
number,boolean,string,function,object,undefined。
我们可以使用typeof来获取一个变量是否存在,如if(typeof a!=“undefined”){alert(“ok”)},而不要去使用if(a)因为如果a不存在(未声明)则会出错,对于Array,Null,DOM对象等特 殊对象使用typeof一律返回object,这正是typeof的局限性。
tyoeof( )的常见运算结果
<script>
alert(typeof (1));
//number
alert(typeof (NaN));
//number
alert(typeof (Infinity));
// number
alert(typeof ("123"));
// string
alert(typeof (true));
// boolean
alert(typeof (window));
// object
alert(typeof (document));
// object
alert(typeof (null));
// object
alert(typeof (eval));
// function
alert(typeof (Date));
// function
alert(typeof (sss));
// undefined
alert(typeof (undefined));
// undefined
</script>
//对于数字类型的操作数而言, typeof 返回的值是 number。比如说:typeof(1),返回的值就是number。
上面是举的常规数字,对于非常规的数字类型而言,其结果返回的也是number。比如typeof(NaN),NaN在
JavaScript中代表的是特殊非数字值,虽然它本身是一个数字类型。
instanceof的介绍
instanceof 运算符用来测试一个对象在其原型链中是否存在一个构造函数的 prototype 属性。
参数:object(要检测的对象.)constructor(某个构造函数)
instanceof 用于判断一个变量是否某个对象的实例,
代码如下:
typeof()和instanceof 的区别
typeof是判断变量是什么基本类型的;
instanceof是判断对象到底是什么类型的;