數據類型檢測

數據類型檢測

1.instanceof

  • 判斷對象是不是構造函數的實例化
  • 能夠用來作判斷已知對象的類型
  • 對象與構造函數在原型鏈上是否有關係
1.    function Person() {
2. this.name = "yaqi";
3. }
4. Person.prototype = {};
5. var p = new Person();
6. console.log(p instanceof Person); // true

2.typeof

  • 數據類型判斷
1.    var num = 1
2. var str = '傳智播客'
3. var bool=false;
4. var arr=[];
5. var obj={name:'傳智播客'};
6. var date = new Date();
7. var fn = function(){}
8.
9. ///******************************************************************************
10. // 數據類型判斷 - typeof
11. //*******************************************************************************
12. console.log('數據類型判斷 - typeof')
13. console.log(typeof undefined)//'undefined'
14. console.log(typeof null) // well-known bug
15. console.log(typeof true) //'boolean'
16. console.log(typeof 123) //'number'
17. console.log(typeof "abc") //'string'
18. console.log(typeof function() {}) //'function'
19. var arr=[];
20. console.log(typeof {}) //'object'
21. console.log(typeof arr)//'object'
22. console.log(typeof unknownVariable) //'undefined'
23. // 在使用 typeof 運算符時採用引用類型存儲值會出現一個問題,
24. // 不管引用的是什麼類型的對象,它都返回 "object"。

3.toString.call()

  • 通用但很繁瑣的方法: 能夠利用Object.prototype.toString.call(arg)來判斷數據類型
1.    console.log('數據類型判斷 - toString.call')
2. console.log(toString.call(123)) //[object Number]
3. console.log(toString.call('123')) //[object String]
4. console.log(toString.call(undefined)) //[object Undefined]
5. console.log(toString.call(true)) //[object Boolean]
6. console.log(toString.call({})) //[object Object]
7. console.log(toString.call([])) //[object Array]
8. console.log(toString.call(function(){})) //[object Function]
9.
10.
11. console.log(Object.prototype.toString.call(str) === '[object String]') //-------> true;
12. console.log(Object.prototype.toString.call(num) === '[object Number]') //-------> true;
13. console.log(Object.prototype.toString.call(arr) === '[object Array]') //-------> true;
14. console.log(Object.prototype.toString.call(date) === '[object Date]') //-------> true;
15. console.log(Object.prototype.toString.call(fn) === '[object Function]') //-------> true;
16.

4.constructor

  • 根據對象的constructor來判斷
1.    // 根據對象的constructor判斷: constructor
2. var arr=[];
3. console.log('數據類型判斷 - constructor')
4. console.log(arr.constructor === Array) //----------> true
5. console.log(date.constructor === Date) //-----------> true
6. console.log(fn.constructor === Function) //-------> true
相關文章
相關標籤/搜索