javascript 中的 typeof

typeof 运算符把传入表达式的类型信息当作字符串返回
1.typeof 返回值有六种可能:”number”、”string”、”boolean”、”object”、”function” 和 “undefined”
2.我们可以使用typeof来获取一个变量是否存在,如if(typeof a!="undefined"){},而不要去使用if(a)因为如果a不存在(未声明)则会出错
3.对于Array,Null等特殊对象使用typeof一律返回object,这正是typeof的局限性

注意:

1.typeof 语法中的圆括号是可选项

2.if(document.mylist.length != “undefined” ) {} 这个用法有误.正确的是 if( typeof(document.mylist.length) != “undefined” ) {}或 if( !isNaN(document.mylist.length) ) {}

3.typeof的运算数未定义,返回的就是 “undefined”

类似的:instanceof

如果我们希望获取一个对象是否是数组,或判断某个变量是否是某个对象的实例,则要选择使用instanceof。instanceof用于判断一个变量是否某个对象的实例

例如:var a=new Array();alert(a instanceof Array);会返回true,同时alert(a instanceof Object)也会返回true;这是因为Array是object的子类。

再如:function test(){};var a=new test();alert(a instanceof test)会返回true。

友情提示:a instanceof Object 得到true并不是因为 Array是Object的子对象,而是因为 Array的prototype属性构造于Object,Array的父级是Function

 

来自:

http://blog.csdn.net/z18842589113/article/details/53315910

http://www.qianduanshiping.com/javascript/

posted @ 2017-11-09 11:18  我将枕中记忆抹去任岁月浮光掠影  阅读(175)  评论(0编辑  收藏  举报