JavaScript 是一種弱型別的腳本語言,共有六種數據類型,可分為三大類:
每個基礎數據類型都有對應的包裝類(Object 物件):Number、String、Boolean。基礎類型會在需要時轉化成包裝物件:
var str = "這是一個基礎字串"; var length = str.length; // 使用 length 時,引擎會產生臨時的 String 物件,用完即清除
(1)typeof:只能辨識 number、string、boolean、undefined、object、function 六種。注意 typeof(null) 會回傳 "object"。
(2)instanceof:可檢測物件是否為另一物件的實例,右運算元必須是物件,但不適合判斷物件本身的型別。
function Animal() {}
function Pig() {}
Pig.prototype = new Animal();
alert(new Pig() instanceof Animal); // true
(3)constructor:可取得物件的建構子,但對 null/undefined 使用會報錯。
(4)Object.prototype.toString():最可靠的型別判斷方式:
function isArray(o) {
return Object.prototype.toString.call(o) === '[object Array]';
}
call 與 apply 的差別:兩者都是 Function.prototype 的方法,作用幾乎相同,差別在於 call 的參數逐一傳入,而 apply 的第二個參數是陣列集合。
(5)綜合寫法:
var _toS = Object.prototype.toString,
_types = {
'undefined' : 'undefined', 'number' : 'number', 'boolean' : 'boolean',
'string' : 'string', '[object Function]' : 'function', '[object RegExp]' : 'regexp',
'[object Array]' : 'array', '[object Date]' : 'date', '[object Error]' : 'error'
};
function type(o) {
return _types[typeof o] || _types[_toS.call(o)] || (o ? 'object' : 'null');
}
基本轉換:
String(678); // "678"
Number("678"); // 678
Boolean("aaa"); // true
從字串中提取數值:
parseInt("123zhang"); // 123
parseFloat("0.55zhang");// 0.55
parseInt 遇到非數字會停止解析,若字串首字元為 0,早期可能被當作八進位處理,導致 parseInt("08") 得到 0。建議永遠明確傳入基數:parseInt("08", 10) 才會得到 8。
此外,parseInt(0.0000001) 會顯示 1,是因為極小數字會以科學記號(1e-7)表示,而 parseInt 會先把參數轉成字串再解析,因此得到 1。使用 parseInt 時務必牢記這一點。