JavaScript 精粹 基礎 進階(1)數據類型
原文連接 http://blog.huanghanlian.com/article/5b698e54b8ea642ea9213f49
數據類型
JavaScript六種數據類型
JavaScript一共有六種數據類型,其中有五種原始類型,和一種對象類型。
JavaScript 隱式轉換
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 當等於一邊是字符串一邊是數字的時候會嘗試把字符串轉換為數字再進行比較
var y=0==false;//true
var e=null==undefined;//true
var c=new Object()==new Object();//false
var d=[1,2]==[1,2];//false
類型不同,嘗試類型轉換和比較
類型不同,嘗試類型轉換和比較:
null == undefined 相等
number == string 轉number 1 == “1.0" // true
boolean == ? 轉number 1 == true // 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 對象應該用引用去比較,而不是用值去比較,因為它們不是完全相同的對象。所以我們定義對象x和y去比較只有這樣才會是true
JavaScript 包裝對象
原始類型number
,string
,boolean
這三種原始類型都有對應的包裝類型。
var a = “string”;
alert(a.length);//6
a.t = 3;
alert(a.t);//undefined
字符串,當把一個基本類型嘗試以對象的方式去使用它的時候,比如訪問length屬性,js會很智能的把基本類型轉換為對應的包裝類型對象。相當於new了string。當完成訪問後,這個臨時對象會被銷毀掉。所以a.t賦值為3後再去輸出a.t值是undefined
JavaScript 類型檢測
類型檢測有以下幾種
- typeof
- instanceof
- Object.prototype.toString
- constructor
- duck type
最常見的typeof
它會返回一個字符串,非常適合函數對象和基本類型的判斷
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
判斷一些基本類型,函數對象的時候非常方便。但是對於其他對象的類型判斷就會沒有辦法了。比如說想判斷一個對象是不是數組,如果用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拿到,適合內置對象和基元類型,遇到null和undefined失效(IE678等返回[object Object])。
instanceof
適合自定義對象,也可以用來檢測原生對象,在不同iframe和window間檢測時失效。
JavaScript 精粹 基礎 進階(1)數據類型