typeof的使用技巧


 typeof  對於基本類型,除了  null  都可以顯示正確的類型

<template>
  <section class="p-10">
    <el-button type="danger" @click="get()">點擊</el-button>
  </section>
</template>
<script> export default { methods: { get() { console.log(typeof '666'); // string
 console.log(typeof 66); // number
 console.log(typeof true); // boolean
 console.log(Symbol()); // Symbol()
 console.log(typeof undefined); // undefined
 console.log(typeof b); // undefined (沒有聲明,但是還是會顯示undefined)
 } } }; </script>

 

 typeof  對於對象,除了函數都會顯示  object 

<template>
  <section class="p-10">
    <el-button type="danger" @click="get()">點擊</el-button>
  </section>
</template>
<script> export default { methods: { get() { console.log(typeof {key: 1}); // object
 console.log(typeof null); // object
 console.log(typeof []); // object
 console.log(typeof function () { // function
 }); } } }; </script>

 

對於  null  來說,雖然它是基本類型,但是會顯示  object ,這是一個存在很久了的 Bug

PS:為什么會出現這種情況呢?因為在 JS 的最初版本中,使用的是 32 位系統,為了性能考慮使用低位存儲了變量的類型信息,000 開頭代表是對象,然而  null  表示為全零,所以將它錯誤的判斷為  object  。雖然現在的內部類型判斷代碼已經改變了,但是對於這個 Bug 卻是一直流傳下來。

 

 

如果我們想獲得一個變量的正確類型,可以通過  Object.prototype.toString.call(xx) 。這樣我們就可以獲得類似  [object Type] 的字符串。

<template>
  <section class="p-10">
    <el-button type="danger" @click="get()">點擊</el-button>
  </section>
</template>
<script> export default { methods: { get() { console.log(Object.prototype.toString.call([1])); console.log(Object.prototype.toString.call(1)); console.log(Object.prototype.toString.call('1')); console.log(Object.prototype.toString.call({})); console.log(Object.prototype.toString.call(true)); console.log(Object.prototype.toString.call(null)); console.log(Object.prototype.toString.call(Symbol())); console.log(Object.prototype.toString.call(function () { })); } } }; </script>

 

 判斷Array的的時候,我們可以使用 instanceof 來判斷,但是這里還要區別 object 

<template>
  <section class="p-10">
    <el-button type="danger" @click="get()">點擊</el-button>
  </section>
</template>
<script> export default { methods: { get() { let a = [1,2]; console.log(a instanceof Array); console.log(a instanceof Object); } } }; </script>

 

 

 

 

 

判斷undefined的時候,有時候我們需要留意一下,undefined 不是保留字,能夠在低版本瀏覽器被賦值,這樣判斷就會出錯

 

<template>
  <section class="p-10">
    <el-button type="danger" @click="get()">點擊</el-button>
  </section>
</template>
<script> export default { methods: { get() { let a; if (a === undefined) { console.log(6); } let undefined = 2; console.log(undefined); if (a === undefined) { console.log(66); } } } }; </script>

所以可以用下面的方式來判斷,並且代碼量更少,因為 void 后面隨便跟上一個組成表達式,返回就是 undefined

<template>
  <section class="p-10">
    <el-button type="danger" @click="get()">點擊</el-button>
  </section>
</template>
<script> export default { methods: { get() { let a; if (a === void 0) { console.log(66); } } } }; </script>

 

 

 

嗯,就醬~

https://www.cnblogs.com/chuhui/archive/2018/12/03/10060071.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM