JavaScript中的typeof操作符用法實例
對一個值使用typeof操作符可能返回下列某個字符串:
“undefined”——如果這個值未定義
“boolean”——如果這個值是布爾值
“string”——如果這個值是字符串
“number”——如果這個值是數(shù)值
“object”——如果這個是對象或null
“function”——如果這個值是函數(shù)
常用的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操作符的操作數(shù)可以是變量(message),也可以是數(shù)值字面量。注意,typeof是一個操作符而不是函數(shù),因此例子中的圓括號不是必須的(盡管可以使用)。
從上面的例子中,我們發(fā)現(xiàn)用Number()創(chuàng)建的數(shù)字也會被typeof判定為對象而返回值“object”,這是因為構造函數(shù)返回的都是對象,那么如果我們想要區(qū)分數(shù)字對象(Number)、字符串對象(String)、數(shù)組對象(Array)、Function對象、日起對象(Date)、布爾對象(Boolean)以及錯誤對象(Error)等JavaScript內(nèi)置對象時,怎么辦呢?在這里可以調(diào)用對象的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]"
// ...
相關文章
Javascript & DHTML 實例編程(教程)基礎知識
Javascript & DHTML 實例編程(教程)基礎知識...2007-06-06小議JavaScript中Generator和Iterator的使用
這篇文章主要介紹了小議JavaScript中Generator和Iterator的使用,文中舉了一個簡單的示例來說明二者之間的配合,需要的朋友可以參考下2015-07-07