前端面試題之JS基本資料型別及判斷
阿新 • • 發佈:2018-12-15
JS基本資料型別有: Number String Boolean Undefined Object(Array,Function) Null Symbol(ES6新增)
其中Array,和Function是Object的子集。 判斷Number,String,Boolean,Undefined,Object,Function直接用typeof:
console.log(typeof 1); //number console.log(typeof '1'); //string console.log(typeof true); //boolean console.log(typeof undefined); //undefined console.log(typeof {}); //object console.log(typeof console.log); //function
判斷Array不能用typeof,因為:
console.log(typeof [1,2,3]); //object
所以要用以下方法判斷:
console.log([1, 2, 3] instanceof Array); //true console.log([1, 2, 3].constructor); //ƒ Array() { [native code] } console.log(Object.prototype.toString.call([1, 2, 3])); //[object Array] console.log(Array.isArray([1, 2, 3])); //true *IE8不相容
判斷Null用===:
console.log(null === null); //true