數(shù)據(jù)類型
JavaScript六種數(shù)據(jù)類型
JavaScript一共有六種數(shù)據(jù)類型傅寡,其中有五種原始類型,和一種對象類型。
JavaScript 隱式轉(zhuǎn)換
var x='The answer'+42;//The answer42
var y=42+'The answer';//42The answer
這里的加號可以理解為字符串的拼接
var x="37"-7; //30
var y="37"+7; //377
這里的減號會理解為減法運算,而加號會理解為字符串拼接
等于判斷
var x="1.23"==1.23;//true 當?shù)扔谝贿吺亲址贿吺菙?shù)字的時候會嘗試把字符串轉(zhuǎn)換為數(shù)字再進行比較
var y=0==false;//true
var e=null==undefined;//true
var c=new Object()==new Object();//false
var d=[1,2]==[1,2];//false
類型不同爪膊,嘗試類型轉(zhuǎn)換和比較
類型不同,嘗試類型轉(zhuǎn)換和比較:
null == undefined 相等
number == string 轉(zhuǎn)number 1 == “1.0" // true
boolean == ? 轉(zhuǎn)number 1 == true // true
object == number | string 嘗試對象轉(zhuǎn)為基本類型 new String('hi') == ‘hi’ // true
其它:false
嚴格等于
a===b
顧名思義砸王,它首先會判斷等號兩邊的類型推盛,如果兩邊類型不同,返回false
如果類型相同谦铃,
類型相同耘成,同===
var h=null===null;//true
var f=undefined===undefined;//true
var g=NaN===NaN;//false number類型它和任何值比較都不會相等,包括和它自己
var l=new Object()===new Object();//false 對象應(yīng)該用引用去比較驹闰,而不是用值去比較瘪菌,因為它們不是完全相同的對象。所以我們定義對象x和y去比較只有這樣才會是true
JavaScript 包裝對象
原始類型number
嘹朗,string
师妙,boolean
這三種原始類型都有對應(yīng)的包裝類型。
var a = “string”;
alert(a.length);//6
a.t = 3;
alert(a.t);//undefined
字符串屹培,當把一個基本類型嘗試以對象的方式去使用它的時候默穴,比如訪問length屬性怔檩,js會很智能的把基本類型轉(zhuǎn)換為對應(yīng)的包裝類型對象。相當于new了string壁顶。當完成訪問后珠洗,這個臨時對象會被銷毀掉。所以a.t賦值為3后再去輸出a.t值是undefined
JavaScript 類型檢測
類型檢測有以下幾種
- typeof
- instanceof
- Object.prototype.toString
- constructor
- duck type
最常見的typeof
它會返回一個字符串若专,非常適合函數(shù)對象和基本類型的判斷
typeof 100 === “number”
typeof true === “boolean”
typeof function () {} === “function”
typeof(undefined) ) === “undefined”
typeof(new Object() ) === “object”
typeof( [1, 2] ) === “object”
typeof(NaN ) === “number”
typeof(null) === “object”
typeof
判斷一些基本類型蝴猪,函數(shù)對象的時候非常方便调衰。但是對于其他對象的類型判斷就會沒有辦法了。比如說想判斷一個對象是不是數(shù)組自阱,如果用typeof
會返回object
顯然不是我想要的嚎莉。
對于判斷對象類型的話,常用obj instanceof Object
[1, 2] instanceof Array === true
new Object() instanceof Array === false
function person(){};
function student(){};
student.prototype=new person();
var bosn =new student();
console.log(bosn instanceof student)//true
var one =new person();
console.log(one instanceof person)//true
console.log(bosn instanceof person)//true
Object.prototype.toString
**IE6/7/8 Object.prototype.toString.apply(null) 返回”[object Object]”
**
Object.prototype.toString.apply([]); === “[object Array]”;
Object.prototype.toString.apply(function(){}); === “[object Function]”;
Object.prototype.toString.apply(null); === “[object Null]”
Object.prototype.toString.apply(undefined); === “[object Undefined]”
typeof
適合基本類型及function檢測沛豌,遇到null失效趋箩。
[[Class]]
通過{}.toString拿到,適合內(nèi)置對象和基元類型加派,遇到null和undefined失效(IE678等返回[object Object])叫确。
instanceof
適合自定義對象,也可以用來檢測原生對象芍锦,在不同iframe和window間檢測時失效竹勉。