JavaScript是弱型別的語言,所以對變數的型別並沒有強制控制型別。所以宣告的變數可能會成為其他型別的變數, 所以在使用中經常會去判斷變數的實際型別。 對於一般的變數我們會使用typeof來判斷變數型別。

  例如:在下面codesandbox中宣告一個變數a,並賦值一個字串'love you forever',然後使用typeof可以獲得指定變數的型別,可以在web-preview看到結果是String型別,再次向變數a賦值數字123,則判斷的型別為number,我再次向變數a賦值一個物件和一個數組,下面的web-preview結果顯示卻都是object,what。這是為什麼?

  所以去MDN查閱相關資料,MDN對於typeof的引數描述內容為"一個表示物件或原始值的表示式"以及對typeof可能返回值如下表:

型別 結果
Undefined "undefined"
Null "object"
Boolean "boolean"
Number "number"
String "string"
Symbol(es6) "symbol"
宿主物件(BOM和DOM) 取決於具體實現
Function "function"
其他物件 "object"

  從表中似乎沒有看到Array的字樣,說明可能包含在其他物件,所以typeof不適合做array的判斷。有沒有其他的方式呢?查閱資料發現四種方法.

  • 構造方法判斷
  let numbers = [1, 2, 3, 4, 5]
let isArray = numbers.construstor === Array ? 'yes' : 'no'
console.log(isArray)
  • 原型判斷
  let numbers = [1, 2, 3, 4, 5]
let isArray = Object.prototype.toString.call(numbers) === '[object Array]' ? 'yes' : 'no'
console.log(isArray)
  • instanceof判斷
  let numbers = [1, 2, 3, 4, 5]
let isArray = numbers instanceof Array ? 'yes' : 'no'
c
  • Array內建的isArray方法判斷
  let numbers = [1, 2, 3, 4, 5]
let isArray = Array.isArray(numbers) ? 'yes' : 'no'
console.log(isArray)

  下面是用codesandbox執行的結果

不知不覺又爬過了一個坑。編碼路上沒有捷徑,沒有程式碼量的積累,就沒有值得飛躍。感謝各位看到這裡,希望大家在不斷地努力下能早日實現自己的前端夢。

.ipad { min-width: 930px; max-width: 930px; min-height: 588px; max-height: 600px; margin-top: 1.5rem; margin-bottom: 1.5rem; border: 1px solid rgba(255, 192, 203, 1); border-radius: 15px; box-shadow: 2px 2px 2px rgba(0, 0, 0, 0.2); display: flex; flex-direction: column; align-items: center; position: relative }
.ipad::before { content: ""; width: 8px; height: 8px; background-color: rgba(0, 0, 0, 1); border-radius: 50%; position: absolute; top: 0.5rem }
.content { margin-top: 1.6rem; margin-bottom: 2.5rem; width: 94%; border: 2px solid rgba(211, 173, 226, 1); border-radius: 3px; overflow: hidden }
.content iframe { margin-bottom: -9px }
{ width: 4px; height: 4px }
{ background-color: rgba(218, 154, 180, 1); border-radius: 4px }
.content:hover { overflow: auto }
.ipad::after { content: ""; width: 24px; height: 24px; background-color: rgba(255, 255, 255, 1); border: 3px solid rgba(255, 165, 0, 1); border-radius: 50%; position: absolute; bottom: 0.3rem }