javascript typeof和instanceof操作符的用法和含义

来源:互联网 发布:淘宝上的红酒能买吗 编辑:程序博客网 时间:2024/04/29 12:08

typeof操作符:由于javascript数据类型是松散的,所以,有时需要检测给定变量的数据类型,typeof操作符负责这类信息的操作。对一个值使用typeof操作符返回下列字符串:

   1> “undefined”---------这个值未定义

   2>  “boolean” ---------这个值是布尔值

   3>  “string”-----------这个值是字符串

   4>  “number”-----------这个值是数值

   5>  “object”-----------这个值是对象或null

   6> “function”----------这个值是函数

eg.

  var message=”I am a string”;

  alert(typeof message)  //”string”

  alert(typeof(message)) //”string”

  alert(typeof 88)       //”Numbe”

  alert(typeof null)     //”object” null被认为是空对象

typeof(eval)              //"function"

typeof(undefined)    //"undefined"

instanceof操作符:在检测基本数据类型时typeof是比较好的选择,但在检测引用类型的值时,typeof操作符功力大减,我们不仅想知道某个值是对象,而且想知道是什么类型的对象

语法为:result= variableinstanceof constructor

eg.

var oStringObject = new String("hello world");  console.log(oStringObject instanceof String);  // 输出 "true"


0 0
原创粉丝点击