本文详细介绍JavaScript中typeof操作符的六种返回值,包括undefined、boolean、string、number、object和function。通过示例展示其用法,并指出typeof将Number、String等包装对象判定为object的局限性。文章进一步讲解利用Object.prototype.toString方法准确区分各类内置对象类型(如Array、Date、Error)的技巧。
typeof操作符的基本返回值类型
对任意值使用typeof操作符,可能返回以下字符串之一:若该值未定义,返回“undefined”;若为布尔值,返回“boolean”;若为字符串,返回“string”;若为数值,返回“number”;若为对象或null,返回“object”;若为函数,返回“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属于操作符而非函数,因此示例中的圆括号并非强制要求(但使用亦无妨)。
利用Object.prototype.toString区分内置对象类型
观察上述示例可知,通过Number()构造函数创建的数字对象,其typeof返回值仍为“object”。这是因为所有构造函数返回的均为对象。若需进一步区分JavaScript内置对象的具体类型,如Number、String、Array、Function、Date、Boolean以及Error等对象,可调用对象的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]"
// ...