ecmascirpt 變數有兩種不同的資料型別:基本型別,引用型別。● boolean
● null
● undefined
● number
● string
● symbol (ecmascript 6 新定義)
● object
物件型別涵蓋了很多引用型別,任何非基本型別的都是物件型別。如function、array、date,這裡就不在贅述。
物件型別:可變型別,支援新增和刪除屬性。var cat = "cat";
cat.color = "black";
cat.color // undefined
基本型別:按值比較,按值傳遞;
物件型別:按引用比較,按引用傳遞。
有四種方法:typeof、instanceof、 constructor、 prototype// 基本型別
var cat = "tom";
var dog = "tom";
cat === dog // true
//物件型別
var cat = ;
var dog = ;
cat === dog //false
例如:
最常見的判斷方法:typeofvar a = "abcdef";
var b = 12345;
var c= [1,2,3];
var d = new date();
var e = function();
var f = function();
其中typeof返回的型別都是字串形式,需注意,例如:alert(typeof a) ------------> string
alert(typeof b) ------------> number
alert(typeof c) ------------> object
alert(typeof d) ------------> object
alert(typeof e) ------------> function
alert(typeof f) ------------> function
另外typeof 可以判斷function的型別;在判斷除object型別的物件時比較方便。alert(typeof a == "string") -------------> true
alert(typeof a == string) ---------------> false
判斷已知物件型別的方法: instanceof
注意:instanceof 後面一定要是物件型別,並且大小寫不能錯,該方法適合一些條件選擇或分支。alert(c instanceof array) ---------------> true
alert(d instanceof date) ---------------> true
alert(f instanceof function) ------------> true
alert(f instanceof function) ------------> false
根據物件的constructor判斷: constructor
注意: constructor 在類繼承時會出錯alert(c.constructor === array) ----------> true
alert(d.constructor === date) -----------> true
alert(e.constructor === function) -------> true
通用但很繁瑣的方法: prototype
注意大小寫。console.log(object.prototype.tostring.call(a)) -------> [object string];
console.log(object.prototype.tostring.call(b)) -------> [object number];
console.log(object.prototype.tostring.call(c)) -------> [object array];
console.log(object.prototype.tostring.call(d)) -------> [object date];
console.log(object.prototype.tostring.call(e)) -------> [object function];
console.log(object.prototype.tostring.call(f)) -------> [object function];
js資料型別及判斷資料型別
1.null 2.undefined 3.boolean 4.number 5.string 6.引用型別 object array function 7.symbol typeof null object typeof undefined undefined typeof true false b...
js資料型別判斷方法
js的資料型別大體上可以分為兩種 原始型別 即基本資料型別 和物件型別 即引用資料型別 而基本資料型別細化可以分為undefined null number boolean string 而js的引用資料型別也就是物件型別object,比如 object array function data等 f...
js中資料型別的判斷的方法
返回資料型別,包含這7種 number boolean symbol string object undefined function。typeof null 返回型別錯誤,返回object 引用型別,除了function返回function型別外,其他均返回object。其中,null 有屬於自己...