美文网首页
typeof 用法详解

typeof 用法详解

作者: JamHsiao_aaa4 | 来源:发表于2018-03-06 17:07 被阅读0次

本文章来介绍在js使用中的一个函数typeof用法, typeof 运算符把类型信息当作字符串返回,包括有大家常有变量类型。

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

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

if(document.mylist.length != “undefined” ) {} 这个用法有误.

正确的是 if( typeof(document.mylist.length) != “undefined” ) {}

或 if( !isNaN(document.mylist.length) ) {}

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

运算数为数字 typeof(x) = “number”

字符串 typeof(x) = “string”

布尔值 typeof(x) = “boolean”

对象,数组和null typeof(x) = “object”

函数 typeof(x) = “function”

typeof 运算符返回一个用来表示表达式的数据类型的字符串。

可能的字符串有:”number”、”string”、”boolean”、”object”、”function” 和 “undefined”。

alert(typeof (123));//typeof(123)返回”number”

alert(typeof (“123″));//typeof(“123″)返回”string”

对于Array,Null等特殊对象使用typeof一律返回object,这正是typeof的局限性。

如果我们希望获取一个对象是否是数组,或判断某个变量是否是某个对象的实例则要选择使用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

相关文章

  • typeof 用法详解

    本文章来介绍在js使用中的一个函数typeof用法, typeof 运算符把类型信息当作字符串返回,包括有大家常有...

  • 详解ECMAScript typeof用法

    typeof 返回变量的类型字符串值 、其中包括 “object”、“number”、“string”、“unde...

  • javascript

    typeof检测类型 用法:alert(typeof.a) 全局函数 eval(...

  • Block中weak/strong self

    Block中weak/strong self用法// 写法 _ typeof _() __typeof() 是对...

  • JavaScript初级篇(二)——typeof操作符,类型转换

    一.typeof操作符 两种写法: (1)typeof()括号 最好用法 (2)typeof object中间加一...

  • js笔记

    typeof 用法 : typeof主要是用于计算表达式以及变量的值类型 for ... in 和 for ...of

  • LiveData

    LiveDataBus实现原理#用法详解#LiveData扩展 LiveDataBus实现原理#用法详解#Live...

  • IOS学习(13)-UITextView

    UITextView详解iOS开发系列之四 – UITextView 用法小结UITextView控件的用法详解

  • typeof的用法

    在js的开发过程中,我们有时可能遇到需要判断变量类型的情况。在js中,我们可以使用typeof运算符来检测一个变量...

  • js typeof用法

    转载文章https://blog.csdn.net/u013362969/article/details/8114...

网友评论

      本文标题:typeof 用法详解

      本文链接:https://www.haomeiwen.com/subject/qjtrfftx.html