【JavaScript高階】1、基礎總結深入(資料型別)
阿新 • • 發佈:2018-12-17
一、資料型別
1. 資料型別分類
* 基本(值)型別
* String: 任意字串
* Number: 任意的數字
* boolean: true/false
* undefined: undefined
* null: null
* 物件(引用)型別
* Object: 任意物件
* Function: 一種特別的物件(可以執行)
* Array: 一種特別的物件(數值下標, 內部資料是有序的)
2. 資料型別判斷
* typeof:
* 可以判斷: undefined/ 數值 / 字串 / 布林值 / function
* 不能判斷: 【 null與object 】 和 【 object與array 】(這三個型別用typeof判斷都返回object)
* instanceof:
* 判斷物件的具體型別
* ===
* 可以判斷: undefined, null
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>01_資料型別</title> </head> <body> <script type="text/javascript"> //1. 基本 // typeof返回資料型別的字串表達 var a console.log(a, typeof a, typeof a==='undefined',a===undefined ) // undefined 'undefined' true true console.log(undefined==='undefined') // false a = 4 console.log(typeof a==='number') // true a = 'chen' console.log(typeof a==='string') // true a = true console.log(typeof a==='boolean') // true a = null console.log(typeof a, a===null) // 'object' null console.log('-----------------') //2. 物件 var b1 = { b2: [1, 'abc', console.log], b3: function () { console.log('b3') return function () { return 'onedean' } } } console.log(typeof b1,typeof a) // object object console.log(typeof b1,typeof b1.b2) // object object console.log(b1 instanceof Object, b1 instanceof Array) // true false 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') // true console.log(typeof b1.b2[2]==='function') // true b1.b2[2](4) // 4 console.log(b1.b3()()) // onedean /*var obj = { name: 'Tom', age: 12 } function test () { var a = 3 } var arr = [3, 'abc'] arr[1]*/ </script> </body> </html>
二、相關問題
1. undefined與null的區別?
* undefined代表定義未賦值
* nulll定義並賦值了, 只是值為null
2. 什麼時候給變數賦值為null呢?
* 初始賦值, 表明將要賦值為物件
* 結束前, 讓物件成為垃圾物件(被垃圾回收器回收)
3. 嚴格區別變數型別與資料型別?
* 資料的型別
* 基本型別
* 物件型別
* 變數的型別(變數記憶體值的型別)
* 基本型別: 儲存就是基本型別的資料
* 引用型別: 儲存的是地址值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>01_相關問題</title>
</head>
<body>
<script type="text/javascript">
// 例項: 例項物件
// 型別: 型別物件
function Person (name, age) {// 建構函式 型別
this.name = name
this.age = age
}
var p = new Person('tom', 12) // 根據型別建立的例項物件
// Person('jack', 12)
// 1. undefined與null的區別?
var a
console.log(a) // undefined
a = null
console.log(a) // null
//起始
var b = null // 初始賦值為null, 表明將要賦值為物件
//確定物件就賦值
b = ['chen', 12]
//最後
b = null // 讓b指向的物件成為垃圾物件(被垃圾回收器回收)
// b = 2
var c = function () {
}
console.log(typeof c) // 'function'
</script>
</body>
</html>