JavaScript中的typeof操作符用法實(shí)例
對(duì)一個(gè)值使用typeof操作符可能返回下列某個(gè)字符串:
“undefined”——如果這個(gè)值未定義
“boolean”——如果這個(gè)值是布爾值
“string”——如果這個(gè)值是字符串
“number”——如果這個(gè)值是數(shù)值
“object”——如果這個(gè)是對(duì)象或null
“function”——如果這個(gè)值是函數(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"
這幾個(gè)例子說明,typeof操作符的操作數(shù)可以是變量(message),也可以是數(shù)值字面量。注意,typeof是一個(gè)操作符而不是函數(shù),因此例子中的圓括號(hào)不是必須的(盡管可以使用)。
從上面的例子中,我們發(fā)現(xiàn)用Number()創(chuàng)建的數(shù)字也會(huì)被typeof判定為對(duì)象而返回值“object”,這是因?yàn)闃?gòu)造函數(shù)返回的都是對(duì)象,那么如果我們想要區(qū)分?jǐn)?shù)字對(duì)象(Number)、字符串對(duì)象(String)、數(shù)組對(duì)象(Array)、Function對(duì)象、日起對(duì)象(Date)、布爾對(duì)象(Boolean)以及錯(cuò)誤對(duì)象(Error)等JavaScript內(nèi)置對(duì)象時(shí),怎么辦呢?在這里可以調(diào)用對(duì)象的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]"
// ...
相關(guān)文章
THREE.JS入門教程(5)你應(yīng)當(dāng)知道的十件事
Three.js是一個(gè)偉大的開源WebGL庫,WebGL允許JavaScript操作GPU,在瀏覽器端實(shí)現(xiàn)真正意義的3D,本文會(huì)讓你了解一下使用THREE.JS處理3D/避免SetInterval/使用倒序循環(huán)等等,感興趣的朋友可以了解下哦2013-01-01Javascript & DHTML 實(shí)例編程(教程)基礎(chǔ)知識(shí)
Javascript & DHTML 實(shí)例編程(教程)基礎(chǔ)知識(shí)...2007-06-06小議JavaScript中Generator和Iterator的使用
這篇文章主要介紹了小議JavaScript中Generator和Iterator的使用,文中舉了一個(gè)簡(jiǎn)單的示例來說明二者之間的配合,需要的朋友可以參考下2015-07-07簡(jiǎn)介JavaScript中的setHours()方法的使用
這篇文章主要介紹了簡(jiǎn)介JavaScript中的setHours()方法的使用,是JS入門學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-06-06