JavaScript中的typeof操作符用法实例


对一个值使用typeof操作符可能返回下列某个字符串:
“undefined”——如果这个值未定义
“boolean”——如果这个值是布尔值
“string”——如果这个值是字符串
“number”——如果这个值是数值
“object”——如果这个是对象或null
“function”——如果这个值是函数

常用的typeof操作符的返回值包括number、string、boolean、undefined 、object和function。如:

复制代码 代码如下:

var n;
console.log(typeof n); // "undefined"

n = 1;
console.log(typeof n); // "number"

n = "1";
console.log(typeof n); // "string"

n = false;
console.log(typeof n); // "boolean"

n = { name: "obj" };
console.log(typeof n); // "object"

n = new Number(5);
console.log(typeof n); // "object"

n = function() { return; };
console.log(typeof n); // "function"

这几个例子说明,typeof操作符的操作数可以是变量(message),也可以是数值字面量。注意,typeof是一个操作符而不是函数,因此例子中的圆括号不是必须的(尽管可以使用)。


从上面的例子中,我们发现用Number()创建的数字也会被typeof判定为对象而返回值“object”,这是因为构造函数返回的都是对象,那么如果我们想要区分数字对象(Number)、字符串对象(String)、数组对象(Array)、Function对象、日起对象(Date)、布尔对象(Boolean)以及错误对象(Error)等JavaScript内置对象时,怎么办呢?在这里可以调用对象的toString方法,如:

复制代码 代码如下:

var n, res;

n = new Number(66);
res = Object.prototype.toString.call(n);
console.log(res); // "[object Number]"

n = new String("string");
res = Object.prototype.toString.call(n);
console.log(res); // "[object String]"

n = [];
res = Object.prototype.toString.call(n);
console.log(res); // "[object Array]"

// ...


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3