您好,欢迎访问一九零五行业门户网

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]
// ...
其它类似信息

推荐信息