1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        4種JavaScript數(shù)據(jù)類型判斷的方法

        共 7591字,需瀏覽 16分鐘

         ·

        2021-05-25 13:35

        來源 | https://www.cnblogs.com/echoyya/p/14416375.html

        今天分享4JavaScript類型判斷的方法:typeof、instanceof、Object.prototype.toString.call()、constructor
        JavaScript數(shù)據(jù)類型
        JavaScript有八種內(nèi)置類型,除對象外,其他統(tǒng)稱為基本類型
        • 空值(null)
        • 未定義(undefined)
        • 布爾值(boolean)
        • 數(shù)字(number)
        • 字符串(string)
        • 對象 (object)
        • 符號(symbol, ES6中新增)
        • 大整數(shù)(BigInt, ES2020 引入)
        Symbol: 是ES6中引入的一種原始數(shù)據(jù)類型,表示獨一無二的值。
        BigInt:是 ES2020 引入的一種新的數(shù)據(jù)類型,用來解決 JavaScript中數(shù)字只能到 53 個二進制位(JavaScript 所有數(shù)字都保存成 64 位浮點數(shù),大于這個范圍的整數(shù),無法精確表示的問題。具體可查看:新數(shù)據(jù)類型 — BigInt

        1、typeof

        typeof是一個操作符而不是函數(shù),其右側(cè)跟一個一元表達式,并返回這個表達式的數(shù)據(jù)類型。返回的結(jié)果用該類型的字符串(全小寫字母)形式表示
        包括以下 8 種:string、number、boolean、undefined、function 、symbol、bigInt、object。
        對于數(shù)組,對象,null以及時間等數(shù)據(jù),typeof只能返回object,而不能直接返回對應(yīng)的類型,還需要通過其他法判斷。
        console.log(typeof "");            // stringconsole.log(typeof 1 );            // numberconsole.log(typeof NaN );          // numberconsole.log(typeof true);          // booleanconsole.log(typeof undefined);     // undefinedconsole.log(typeof function(){});  // functionconsole.log(typeof isNaN);         // functionconsole.log(typeof Symbol());      // symbolconsole.log(typeof 123n);          // bigintconsole.log(typeof []);            // objectconsole.log(typeof {});            // objectconsole.log(typeof null);          // objectconsole.log(typeof new Date());    // objectconsole.log(typeof new RegExp());  // object

        2、instanceof

        instanceof 是用來判斷 A 是否為 B 的實例,表達式為:A instanceof B,如果 A 是 B 的實例,則返回 true,否則返回 false。 需特別注意:instanceof 檢測的是原型

        即instanceof 用來比較一個對象是否為某一個構(gòu)造函數(shù)的實例。instanceof可以準(zhǔn)確的判斷復(fù)雜數(shù)據(jù)類型,但是不能正確判斷基本數(shù)據(jù)類型。

        console.log(12 instanceof Number);                 // falseconsole.log('22' instanceof String);               // falseconsole.log(true instanceof Boolean);              // falseconsole.log(null instanceof Object);               // falseconsole.log(undefined instanceof Object);          // falseconsole.log(function a() {} instanceof Function);  // trueconsole.log([] instanceof Array);                  // trueconsole.log({a: 1} instanceof Object);             // trueconsole.log(new Date() instanceof Date);           // true

        補充:

        instanceof 的原理:主要的實現(xiàn)原理就是只要右邊變量的 prototype在左邊變量的原型鏈上即可。
        因此,instanceof 在查找的過程中會遍歷左邊變量的原型鏈,直到找到右邊變量的 prototype,如果存在返回true 否則返回false

        function new_instance_of(leftVaule, rightVaule) {     let rightProto = rightVaule.prototype; // 取右表達式的 prototype 值    leftVaule = leftVaule.__proto__; // 取左表達式的__proto__值    while (true) {      if (leftVaule === null) {            return false;          }        if (leftVaule === rightProto) {            return true;          }         leftVaule = leftVaule.__proto__     }}

        注意:instanceof 運算時會遞歸查找leftVaule的原型鏈,即leftVaule.__proto__.__proto__.__proto__.__proto__... 直到找到了或者找到頂層為止。

        一句話理解其運算規(guī)則:instanceof 檢測左側(cè)的 __proto__ 原型鏈上,是否存在右側(cè)的 prototype 原型。

        3、constructor

        1. JavaScript中,每個對象都有一個constructor屬性,可以得知某個實例對象,到底是哪一個構(gòu)造函數(shù)產(chǎn)生的, constructor屬性表示原型對象與構(gòu)造函數(shù)之間的關(guān)聯(lián)關(guān)系。

        • 當(dāng)一個函數(shù)F被定義時,JS引擎會為F添加prototype原型,然后在prototype上添加一個constructor屬性,并讓其指向F的引用,F(xiàn)利用原型對象的constructor屬性引用了自身,當(dāng)F作為構(gòu)造函數(shù)創(chuàng)建對象時,原型上的constructor屬性被遺傳到了新創(chuàng)建的對象上,從原型鏈角度講,構(gòu)造函數(shù)F就是新對象的類型。這樣做的意義是,讓對象誕生以后,就具有可追溯的數(shù)據(jù)類型。

        • 通過typeof運算符來判斷它是原始的值還是對象。如果是對象,就可以使用constructor屬性來判斷其類型。

        • 如判斷數(shù)組的函數(shù):

        function isArray(data){   return typeof data == "object" && data.constructor == Array; }isArray([])  // true

        注意:null 和 undefined 是沒有 constructor 存在的,這兩種類型的數(shù)據(jù)需要通過其他方式來判斷。

        console.log('22'.constructor === String)             // trueconsole.log(true.constructor === Boolean)            // trueconsole.log([].constructor === Array)                // trueconsole.log(document.constructor === HTMLDocument)   // trueconsole.log(window.constructor === Window)           // trueconsole.log(new Number(22).constructor === Number)   // trueconsole.log(new Function().constructor === Function) // trueconsole.log(new Date().constructor === Date)         // trueconsole.log(new RegExp().constructor === RegExp)     // trueconsole.log(new Error().constructor === Error)       // true

        2、如果修改了原型對象,一般會同時修改constructor屬性,防止引用的時候出錯。所以,修改原型對象時,一般要同時修改constructor屬性的指向。

        function Rectangle(width, height){    this.width = width;    this.height = height;    this.getArea = function(){        return '矩形的面積為' + (width * height);    }}
        var rect1 = new Rectangle(40, 20);var rect2 = new Rectangle(50, 20);var rect3 = new Rectangle(60, 20);console.log(rect1.getArea());console.log(rect2.getArea());console.log(rect3.getArea());
        • 如上代碼,每次實例化出一個對象,都會添加getArea方法,是三個對象共有且不變的,因此將getArea放在構(gòu)造函數(shù)中就會在創(chuàng)建對象時被多次添加,浪費內(nèi)存!

        • 因此我們將getArea添加到原型對象上就減少了多次添加,實例化對象會沿著原型鏈查找到此屬性

        • 實現(xiàn)了共享屬性:

        function Rectangle(width, height){    this.width = width;    this.height = height;}
        // 直接替換原型對象,但是要記得添加上構(gòu)造函數(shù)屬性Rectangle.prototype = { constructor: Rectangle, getArea: function(){ return '矩形的面積為' + (this.width * this.height); }}
        // 修改特性Object.defineProperties(Rectangle.prototype, { constructor: { enumerable: false, configurable: false, writable: false }, getArea: { enumerable: false, configurable: false, writable: false }})
        var rect1 = new Rectangle(40, 20);var rect2 = new Rectangle(50, 20);var rect3 = new Rectangle(60, 20);console.log(rect1.getArea());console.log(rect2.getArea());console.log(rect3.getArea());

        很多情況下,我們可以使用instanceof運算符或?qū)ο蟮腸onstructor屬性來檢測對象是否為數(shù)組。

        如很多JS框架就是使用這兩種方法來判斷對象是否為數(shù)組類型。 但是檢測在跨框架(cross-frame)頁面中的數(shù)組時,會失敗。

        原因就是在不同框架(iframe)中創(chuàng)建的數(shù)組不會相互共享其prototype屬性。例如:

         <script>     window.onload=function(){         var iframe_arr=new window.frames[0].Array;         console.log(iframe_arr instanceof Array);     // false         console.log(iframe_arr.constructor == Array); // false     }</script>

        4、Object.prototype.toString.call()

        • Object.prototype.toString(o)是 Object 的原型方法,

          1. 獲取對象o的class屬性。這是一個內(nèi)部屬性,

          2. 連接字符串:[object + 結(jié)果(1)],格式為 [object Xxx] ,其中 Xxx 就是對象的類型。

        • 對于 Object 對象,直接調(diào)用 toString() 就能返回 [object Object] 。而對于其他對象,則需要通過 call / apply 來調(diào)用才能返回正確的類型信息。

          console.log(Object.prototype.toString.call(1))          // [object Number]  console.log(Object.prototype.toString.call(1n))         // [object BigInt]  console.log(Object.prototype.toString.call('123'))      // [object String]  console.log(Object.prototype.toString.call(true))       // [object Boolean]  console.log(Object.prototype.toString.call(undefined))  // [object Undefined]  console.log(Object.prototype.toString.call(null))       // [object Null]  console.log(Object.prototype.toString.call({}))         // [object Object]  console.log(Object.prototype.toString.call([]))         // [object Array]  console.log(Object.prototype.toString.call(function a() {}))  // [object Function]  console.log(Object.prototype.toString.call(Symbol()))         // [object Symbol]  console.log(Object.prototype.toString.call(Math))             // [object Math]  console.log(Object.prototype.toString.call(JSON))             // [object JSON]  console.log(Object.prototype.toString.call(new Date()))       // [object Date]  console.log(Object.prototype.toString.call(new RegExp()))     // [object RegExp]  console.log(Object.prototype.toString.call(new Error))        // [object Error]  console.log(Object.prototype.toString.call(window)            // [object Window]  console.log(Object.prototype.toString.call(document))         // [object HTMLDocument]

        封裝一個準(zhǔn)確判斷數(shù)據(jù)類型的函數(shù)

          function __getType(object){    return Object.prototype.toString.call(object).match(/^\[object\s(.*)\]$/)[1];  };

        可以解決上面的跨框架問題。

          <script>      window.onload=function(){          var iframe_arr=new window.frames[0].Array;          console.log(Object.prototype.toString.call(iframe_arr)))  // "[object Array]"      }</script>

        本文完~


        學(xué)習(xí)更多技能

        請點擊下方公眾號

        瀏覽 47
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        評論
        圖片
        表情
        推薦
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            欧美亚洲日本韩国高清色图 | 国产露脸8mav | 日韩欧美在线观看一区二区 | 青娱乐性爱视频 | 全文辣肉h短篇春野小农民视频 | 人妻无码аⅴ天堂中文在线 | 永久免费的成人电影 | 亚州不卡 | 国产自产精品一区精品 | 国模自拍一区 |