《JavaScript程序設計》第2課:JS類型系統

JS類型系統能夠分爲標準類型和對象類型,進一步標準類型又能夠分爲原始類型和引用類型,而對象類型又能夠分爲內置對象類型、普通對象類型、自定義對象類型。git

1. 標準類型

標準類型共包括了6個分別是:undefined Null Boolean Number String Object,其中undefined Null Boolean Number String是原始類型,而Object是引用類型。其聲明方式以下:github

var a;    //undefined
var b = document.getElementById("no_exist_element"); //null
var c = true;    //Boolean
var d = 1;    //Number
var e = "str";     //String
var f = {name : "Tom"};    //Object

原始類型和引用類型的區別:正則表達式

原始類型儲存在棧(Stack)中儲存變量的值,而引用類型在棧中保存的是所引用內容儲存在堆(Heap)中的值。相似於指針的概念,引用類型並不是儲存變量真實數值而是地址,因此對已引用類型的複製其實只是複製了相同的地址而非實際的變量值。express

1.1 Undefined 編程

值:undefinedjson

出現場景:數組

- 已聲明未賦值的變量 var obj;安全

- 獲取對象不存在的屬性 var obj = {x: 0}; obj.y;app

- 無返回值函數的執行結果 function f(){}; var obj = f();dom

- 函數參數沒有傳入 function f(i){console.log(i)}; f();

- void(expression)

1.2 Null

值:null

出現場景:

- 獲取不存在的對象 document.getElementById('not-exist-element')

1.3 Boolean

值:true false

出現場景:

- 條件語句致使的系統執行的隱式類型轉換 if(隱式轉換){}

if(document.getElementById('not-exist-element')){
    //
}else{
    //執行這裏的代碼
}

上面的if(document.getElementById('not-exist-element'))等於if(Boolean(document.getElementById('not-exist-element')))

- 字面量或變量定義 var bool = true;

1.4 String

值:字符串

出現場景:

直接聲明 var str = 'Hello, world!';

1.5 Number

值:整型直接量,八進制直接量(0-),十六進制直接量(0x-),浮點型直接量

出現場景:

- 1026

- 1.2e5

- 010

- 0x10

- 3.14

1.6 Object

值:屬性集合

出現場景:

- var obj = {name: 'Xinyang'};

1.7 變量轉換表

Value Boolean Number String
undefined false NaN "undefined"
null false 0 "null"
true true 1 "true"
false false 0 "false"
'' false 0 ''
'123' true 123 '123'
'1a' true NaN '1a'
0 false 0 "0"
1 true 1 "1"
Infinity true Infinity "Infinity"
NaN false NaN 'NaN'
{} true NaN "[object Object]"

2.對象類型

2.1 內置對象類型

內置對象,其實也叫內置構造器,它們能夠經過new方式建立一個新的對象。內置對象所屬的類型就叫內置對象類型。

內置對象一共有9個,分別是:Boolean String Number Object Array Date Error Function RegExp。其聲明方式以下:

var g = new Boolean(true);    //Boolean Object
var h = new Number(1);    //Number Object
var i = new String("str");    //String Object
var j = new Object({name : "Tom"}); //Object Object 
var k = new Array([1, 2, 3, 4]);    //Array Object
var l = new Date();    //Date Object
var m = new Error();
var n = new Function();    
var o = new RegExp("\\d");

要注意,雖然標準類型中有Boolean String Number Object,內置對象類型中也有Boolean String Number Object,但它們實際上是經過不一樣的聲明方式來進行區別的。標準類型經過直接賦值,而對象類型則是經過構造器實現初始化。

var stdType = "hello";  //標準類型
var objType = new String("hello");  //對象類型

上面兩種聲明方式,stdType是標準類型,而objType是對象類型。

2.1.1 Object

(1)實例化方法

var obj0 = new Object({name: 'X', age: 13});
// 經常使用方法
var obj1 = {name: 'Q', age: 14};

(2)屬性及方法(至關於類的靜態方法)

prototype、create、keys...

(3)原型對象屬性及其方法(至關於父類的方法)

constructor、toString、valueOf、hasOwnProperty...

(4)實例對象屬性及方法(至關於實例化後才能調用的方法) 

(5)舉例

Object.create

功能:基於原型對象創造新對象

// objectInstance.toString()
var obj = {};
obj.toString(); // Object

Object.prototype.hasOwnProperty

功能:判斷一個屬性是不是一個對象的自身屬性

// objectInstance.hasOwnProperty("propertyName")
var obj = Object.create({a: 1, b: 2});
obj.c = 3;
obj.hasOwnProperty('a'); // false
obj.hasOwnProperty('c'); // true

2.1.2 Boolean 

(1)實例化方法

var flag = new Boolean("true");

(2)屬性及方法(至關於類的靜態方法)

prototype

(3)原型對象屬性及其方法(至關於父類的方法)

constructor, toString, valueOf...

(4)實例對象屬性及方法(至關於實例化後才能調用的方法) 

2.1.3 String

(1)實例化方法

'Hello, world!'
var str0 = 'Xinyang';
var str1 = new String('Xinyang');

(2)屬性及方法(至關於類的靜態方法)

prototype、fromCharCode(轉換 ASCII 代碼爲字符)

(3)原型對象屬性及其方法(至關於父類的方法)

constructor、indexOf、replace、slice、split、charCodeAt、toLowerCase

(4)實例對象屬性及方法(至關於實例化後才能調用的方法) 

(5)例子

String.prototype.indexOf

功能:獲取子字符串在字符串中的索引

// stringObject.indexOf(searchValue, fromIndex)
var str = "I am X. From China!";
var index = str.indexOf('a'); // 2
str.indexOf('a', index + 1); // 16
str.indexOf('Stupid'); // -1 字符串不存在

String.prototype.replace

功能:查找字符串替換成目標文字

// stringObject.replace(regexp/substr, replacement)
var str = "apple is bad";
str = str.replace('bad', 'awesome');

String.prototype.split

功能:按分隔符將分隔符分紅字符串數組

// stringObject.split(separator, arrayLength)
var str = '1 2 3 4';
str.split(' '); // ['1', '2', '3', '4'];
str.split(' ', 3); // ['1', '2', '3'];
str.split(/\d+/); // ["", " ", " ", " ", ""]

2.1.4 Number

(1)實例化方法

var num = new Number("10");

(2)屬性及方法(至關於類的靜態方法)

  • prototype
  • MAX_VALUE
  • MIN_VALUE
  • NaN
  • NEGATIVE_INFINITY
  • POSITIVE_INFINITY

(3)原型對象屬性及其方法(至關於父類的方法)

  • constructor
  • toFixed
  • toExponential
  • ...

(4)實例對象屬性及方法(至關於實例化後才能調用的方法) 

(5)例子 

Number.prototype.toFixed

功能:四捨五入至指定小數位

// numberObject.toFixed(num)
var num0 = 3.14;
num0.toFixed(1); // 3.1
var num1 = 3.35;
num1.toFixed(1); // 3.4

2.1.5 Array

(1)實例化方法

var a2 = new Array(1, 'abc', true);

(2)屬性及方法(至關於類的靜態方法)

  • prototype
  • isArray

(3)原型對象屬性及其方法(至關於父類的方法)

  • constructor
  • splice
  • forEach
  • find
  • concat
  • pop
  • push
  • reverse
  • shift
  • slice

(4)實例對象屬性及方法(至關於實例化後才能調用的方法) 

  • length

(5)例子 

Array.prototype.splice

功能:從數組中刪除或添加元素,返回被刪除的元素列表(做用於原有數組)

// arrayObject.splice(start, deleteCount[, addedItem1[, addedItem2[, ...]]])
var arr = ['1', '2', 'a', 'b', '6'];
var ret = arr.splice(2, 2, '3', '4', '5'); // ['a', 'b']
arr; // ['1', '2', '3', '4', 5', '6']

Array.prototype.forEach

功能:遍歷元素組並調用回調函數

// arrayObject.forEach(callback[, thisArg])
// 回調函數
// function callback(value, index, arrayObject) {...}
// value - 當前值 index - 當前索引 arrayObject - 數組自己
function logArray(value, index, arrayObject) {
  console.log(value);
  console.log(value === array[index]);
}
[2, 5,  , 9].forEach(logArray);

2.1.6 Function

(1)實例化方法

// 對象實例化
var f0 = new Function('i', 'j', 'return (i + j)'); // 函數關鍵字語句 function f1(i, j){return i + j;} // 函數表達式 var f3 = function(i, j){return i + j;};

(2)屬性及方法(至關於類的靜態方法)

  • prototype

(3)原型對象屬性及其方法(至關於父類的方法)

  • constructor
  • apply
  • call
  • bind

(4)實例對象屬性及方法(至關於實例化後才能調用的方法) 

  • length 實參個數
  • prototype
  • arguments
  • caller 調用者

(5)例子 

Function.prototype.apply

功能:經過參數指定調用者和函數參數並執行該函數

// functionObj.apply(thisArg[, argsArray])
function Point(x, y) {
  this.x = x;
  this.y = y;
}

Point.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
}

var p = new Point(1, 1);
var circle = {x: 1, y: 1, r: 1};
p.move.apply(circle, [2, 1]); // {x: 3, y: 2, r: 1}

Function.prototype.bind

功能:經過參數指定函數調用者和函數參數並返回該函數的引用

// functionObj.bind(thisArg[, arg1[, arg2[, ...]]])
function Point(x, y) {
  this.x = x;
  this.y = y;
}

Point.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
}

var p = new Point(1, 1);
var circle = {x: 1, y: 1, r: 1};
var circleMoveRef = p.move.bind(circle, 2, 1);
setTimeout(circleMoveRef, 1000); // {x: 3, y: 2, r: 1}

//去掉setTimeout(...)語句而直接使用 circleMoveRef() 效果等同於 apply()
//circleMoveRef();

2.1.7 RegExp

(1)實例化方法

var regExp = new RegExp(/\d+/i);

(2)屬性及方法(至關於類的靜態方法)

  • prototype

(3)原型對象屬性及其方法(至關於父類的方法)

  • constructor
  • test
  • exec
  • ...

(4)實例對象屬性及方法(至關於實例化後才能調用的方法) 

(5)例子 

RegExp.prototype.test

功能:使用正則表達式對字符串進行測試,並返回測試結果

// regexObj.text(str)
var reg = /^abc/i;
reg.test('Abc123'); // true
reg.test('1Abc1234'); // false

2.1.8 Date

(1)實例化方法

var date0 = new Date(); var date1 = new Date(2014, 3, 1, 7, 1, 1, 100);

(2)屬性及方法(至關於類的靜態方法)

  • prototype
  • parse
  • now
  • ...

(3)原型對象屬性及其方法(至關於父類的方法)

  • constructor
  • Date
  • getDate
  • getHours
  • setDate
  • setHours
  • ...

(4)實例對象屬性及方法(至關於實例化後才能調用的方法) 

2.2 普通對象類型

普通對象類型包括Math、JSON、全局對象三種,普通對象類型的特色就是其直接能夠經過Math.method方式調用,相似於工具類同樣,能夠直接經過類調用靜態方法。如:Math.random()返回一個0-1之間的隨機數,JSON.parse(jsonStr)解析JSON字符串爲JSON對象……

2.2.1 Math

(1)對象說明

擁有屬性和方法的單一對象主要用於數字計算

(2)對象屬性

  • E
  • PI
  • SQRT2
  • ...

(3)對象方法

  • floor
  • random
  • abs
  • max
  • cos
  • ceil
Math.floor

功能:向下取整

// Math.floor(num)
Math.floor(0.97); // 0
Math.floor(5.1); // 5
Math.floor(-5.1); //6

類似方法:ceilround

Math.random

功能:返回 0~1 之間的浮點數

// Math.random()
Math.random(); // 0.14523562323461

2.2.2 JSON

(1)對象說明

用於存儲和交換文本信息

(2)對象方法

  • parse
  • stringify
JSON.stringify

功能:將 JSON 對象轉換爲字符轉

// JSON.stringify(value[, replacer[, space]])
var json = {'name': 'X'};
JSON.stringify(json); // "{"name":"X"}"
JSON.parse

功能:將 JSON 字符轉轉換爲對象

// JSON.parse(text[, reviver])
var jsonStr = '{"name":"X"}';
JSON.parse(jsonStr); // {name: 'X'}

2.2.3 全局對象

全局對象定義了一系列的屬性和方法在編程過程當中能夠被之間調用。

(1)屬性

NaN,Infinity,undefined

(2)方法

  • parseInt
  • parseFloat
  • isNaN
  • isFinite
  • eval

處理 URI 方法:

  • encodedURIComponent
  • decodeURIComponent
  • encodedURI
  • decodeURI

構造器屬性:

  • Boolean
  • String
  • Number
  • Object
  • Function
  • Array
  • Date
  • Error
  • ...

對象屬性:

  • Math
  • JSON
NaN

非數字值:表示錯誤或無心義的運算結果,NaN 參與運算仍會返回 NaA,且 NaN 不等於任何值,包括它自己。可使用isNaN() 判斷運算結果的類型是否爲 NaN。

isNaN(NaN); // true
isNaN(4 - '2a'); // flase;
parseInt

功能:轉換字符串成數字

// parseInt(string[, radix])
// radix - 爲進制數
parseInt('010'); // 10
parseInt('010', 8) // 8
parseInt('010', 15) // 16

parseInt('0x1f'); // 31
parseInt('0x1f', 16); // 31
parseInt('1f'); // 1
parseInt('1f', 16); // 32
eval

功能:計算字符串並執行其中的 JavaScript 代碼(會帶來安全性和代碼邏輯問題,一般不建議使用)

// eval(string)
var res = '{"error": "0", "msg": "OK"};
var obj;
if (!JSON) {
  obj = eval('(' + res + ')');
} else {
  obj = JSON.parse(res);
}
encodedURIComponent

功能:將 URI 參數中的特殊字符,中文等做爲 URI 的一部分進行編碼

var uri = "http://w3schools.com/my test.asp?name=ståle&car=saab";
var res = encodeURIComponent(uri);

// 結果
// http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab

2.3 自定義對象類型

自定義對象類型就是本身定義的對象,能夠理解成Java中的類。

function Point(x, y) {
  this.x = x;
  this.y = y;
}

Point.prototype.move = function(x, y) {
  this.x += x;
  this.y += y;
}

var p = new Point(1, 2);

上面代碼聲明一個Point對象,併爲Point對象增長了一個move方法,最後建立了一個Point對象。

相關文章
相關標籤/搜索