【1】JavaScript 基礎深刻——數據類型深刻理解與總結

數據類型深刻理解

數據類型分類

基本(值)類型(6種)

  • String:任意字符串
  • Number:任意的數字
  • booleantrue/false
  • nullnull
  • undefinedundefined
  • Symbol: ES6新增,表示獨一無二的值

對象(引用)類型(3種)

  • Object:任意對象
  • Array:一種特別的對象(數值下標,內部數據是有序的)
  • Function:一種特別的對象(能夠執行)

數據類型判斷(3種方式)

typeof :返回數據類型的字符串表達

var a
console.log(a) // undefined
console.log(typeof a) // "undefined"
console.log(a === undefined) // true
console.log(typeof a === undefined) // false
console.log(typeof a === "undefined") // true
console.log(undefined === "undefined") // false

a = 4
console.log(typeof a) // "number"
console.log(typeof a === Number) // false
console.log(typeof a === "number") // true

a = "hahha"
console.log(typeof a) // "string"

a = false
console.log(typeof a) // "boolean"

a = null
console.log(typeof a) // object
console.log(a === null) // true

注意:typeof返回的是數據類型的字符串表達形式。javascript

typeof true //"boolean"
typeof "hahha" //"string"
typeof 12 //"number"
typeof null //"object"
typeof ccc //"undefined"

typeof function(){} //"function"
typeof {} //"object"

instanceof:類型的實例

首先要理解 instanceof的含義:
  • instance例子的意思,A instanceof B 其實是判斷A是不是B的一個實例。理解了這一點,就不難判斷類型了。
var b1 = {
    b2: [1, "hehe", console.log],
    b3: function () {
        console.log("b3")
        return function  () {
            return "Mandy"
        }
    }
}

console.log(b1 instanceof Object) // true
console.log(b1.b2 instanceof Array, b1.b2 instanceof Object) // true true
console.log(b1.b3 instanceof Function, b1.b3 instanceof Object) //true true

console.log(typeof b1.b2) // "object"
console.log(typeof b1.b3) // "function"
console.log(typeof b1.b2[1]) // "string"
console.log(typeof b1.b2[2]) // "function"
b1.b2[2](555) // 555
console.log(b1.b3()()) // "b3" "Mandy"

注意:java

  • 函數既是 Function 類型,也是 Object 類型
  • 數組既是 Array 類型,也是 Object 類型

===

  • 能夠判斷undefined null
ccc === "undefined" // true
null === null // true

總結

  • typeof :數組

    • 能夠判斷 undefined / 數值 / 字符串 / 布爾值 / function
    • 不能判斷 nullobject, arrayobject函數

      typeof null // "object"
      
      typeof [] // "object"
  • instanceof:ui

    • 判斷對象的具體類型
    • A instanceof B
  • ===:this

    • 能夠判斷 undefined , null

undefinednull 的區別?

  • undefined 表明定義了,未賦值
  • null 表明定義了,而且賦值了,只是賦的值爲 null
// undefined與null的區別?
var a
console.log(a)  // undefined
a = null
console.log(a) // null

何時給變量賦值爲null?

  • 初始賦值,代表將要賦值爲對象。由於 typeof null === "Object"
  • 結束前,讓對象成爲垃圾對象(被垃圾回收器回收)
//起始
var b = null  // 初始賦值爲null, 代表將要賦值爲對象
//肯定對象就賦值
b = ['atguigu', 12]
//最後
b = null // 讓b指向的對象成爲垃圾對象(被垃圾回收器回收)

嚴格區別變量類型數據類型

  • 數據的類型:code

    • 基本類型
    • 對象類型
  • 變量的類型(變量內存值的類型)對象

    • 基本(值)類型:保存的就是基本類型的數據
    • 引用類型:保存的是地址值

理解實例類型

// 實例: 實例對象
// 類型: 類型對象
function Person (name, age) {// 構造函數  類型
  this.name = name
  this.age = age
}
var p = new Person('tom', 12) // 根據類型建立的實例對象
相關文章
相關標籤/搜索