JavaScript中的typeof操作符用法实例 |
对一个值使用typeof操作符可能返回下列某个字符串: 常用的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是一个操作符而不是函数,因此例子中的圆括号不是必须的(尽管可以使用) 。
复制代码 代码如下: 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]" // ... |