title
stringlengths
2
136
text
stringlengths
20
75.4k
Array.prototype.flat() - JavaScript
Array.prototype.flat() ====================== Baseline Widely available ------------------------- This feature is well established and works across many devices and browser versions. It’s been available across browsers since January 2020. * Learn more * See full compatibility * Report feedback **實驗性質:** **這是一個實驗中的功能 (en-US)** 此功能在某些瀏覽器尚在開發中,請參考兼容表格以得到不同瀏覽器用的前輟。 **`flat()`** 函數以遞迴方式將特定深度的子陣列重新串接成為一新的陣列 嘗試一下 ---- 語法 -- ```js var newArray = arr.flat([depth]); ``` ### 參數 `depth` 選擇性 指定巢狀陣列展開的深度。預設為 1。 ### 回傳值 函數將會回傳一個由原先陣列的子陣列串接而成的新陣列。 範例 -- ### 展開巢狀陣列 ```js var arr1 = [1, 2, [3, 4]]; arr1.flat(); // [1, 2, 3, 4] var arr2 = [1, 2, [3, 4, [5, 6]]]; arr2.flat(); // [1, 2, 3, 4, [5, 6]] var arr3 = [1, 2, [3, 4, [5, 6]]]; arr3.flat(2); // [1, 2, 3, 4, 5, 6] ``` ### 當遭遇空元素時 `flat()` 函數會自動清除陣列中空的元素 ```js var arr4 = [1, 2, , 4, 5]; arr4.flat(); // [1, 2, 4, 5] ``` 替代方案 ---- ### `reduce` 與 `concat` ```js var arr1 = [1, 2, [3, 4]]; arr1.flat(); //展開單層陣列 arr1.reduce((acc, val) => acc.concat(val), []); // [1, 2, 3, 4] ``` ```js //欲展開更深層的巢狀結構請使用reduce與concat的遞迴 function flattenDeep(arr1) { return arr1.reduce( (acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), [], ); } flattenDeep(arr1); // [1, 2, 3, 1, 2, 3, 4, 2, 3, 4] ``` ```js //使用stack來實作非遞迴的展開 var arr1 = [1, 2, 3, [1, 2, 3, 4, [2, 3, 4]]]; function flatten(input) { const stack = [...input]; const res = []; while (stack.length) { // pop value from stack const next = stack.pop(); if (Array.isArray(next)) { // push back array items, won't modify the original input stack.push(...next); } else { res.push(next); } } //reverse to restore input order return res.reverse(); } flatten(arr1); // [1, 2, 3, 1, 2, 3, 4, 2, 3, 4] ``` ```js // 递归版本的反嵌套 function flatten(array) { var flattend = []; (function flat(array) { array.forEach(function (el) { if (Array.isArray(el)) flat(el); else flattend.push(el); }); })(array); return flattend; } ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-array.prototype.flat | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Array.prototype.flatMap()` (en-US) * `Array.prototype.map()` * `Array.prototype.reduce()` * `Array.prototype.concat()`
Array.length - JavaScript
Array.length ============ **`length`** 為 `Array` 物件的屬性,可供設定或回傳該陣列實體中包含的元素個數。其值必為一大於零、32 位元、且恆大於該陣列最大索引數的正整數。 ```js var items = ["shoes", "shirts", "socks", "sweaters"]; items.length; // returns 4 ``` 描述 -- `length` 屬性的值必為一正整數,其值必介於 0 ~ 2^32 (不包含)之間. ```js var namelistA = new Array(4294967296); //2^32 = 4294967296 var namelistC = new Array(-100); //負數 console.log(namelistA.length); //RangeError: Invalid array length console.log(namelistC.length); //RangeError: Invalid array length var namelistB = []; namelistB.length = Math.pow(2, 32) - 1; //將長度設定介於 0 ~ 2^32 -1 console.log(namelistB.length); //4294967295 ``` 你可以透過改變 `length` 屬性來改變陣列的長度。當你透過 `length` 屬性來增加陣列的長度時,陣列中實際的元素也會隨之增加。舉例來說,當你將 array.length 由 2 增加為 3,則改動後該陣列即擁有 3 個元素,該新增的元素則會是一個不可迭代(non-iterable)的空槽(empty slot)。 ``` const arr = [1, 2]; console.log(arr); // [ 1, 2 ] arr.length = 5; // 將arr的length由2改成5 console.log(arr); // [ 1, 2, <3 empty items> ] arr.forEach(element => console.log(element)); // 空元素無法被迭代 // 1 // 2 ``` 如上所見,`length` 屬性不盡然代表陣列中所有已定義的元素個數。詳見 length 與數值屬性的關係。 | `Array.length` 的屬性特性 | | --- | | 可寫 | 是 | | 可列舉 | 否 | | 可配置 | 否 | * `Writable`: 如果此屬性值為`false`,則該屬性的內容值無法被改動。 * `Configurable`: 如果此屬性值為`false`,任何刪除屬性或更改其屬性的操作(`Writable`, `Configurable`, or `Enumerable`)皆會失敗。 * `Enumerable`: 如果此屬性值為`true`,該內容值可倍 for 或 for..in 迴圈迭代處理。 範例 -- ### 對陣列進行迭代處理 以下範例中, 陣列 `numbers` 透過 `length` 屬性進行迭代操作,並將其內容值加倍。 ```js var numbers = [1, 2, 3, 4, 5]; var length = numbers.length; for (var i = 0; i < length; i++) { numbers[i] \*= 2; } // numbers 內容值變為 [2, 4, 6, 8, 10] ``` ### 縮減陣列 以下範例中, 陣列 `numbers` 的長度若大於 3,則將其長度縮減至 3。 ```js var numbers = [1, 2, 3, 4, 5]; if (numbers.length > 3) { numbers.length = 3; } console.log(numbers); // [1, 2, 3] console.log(numbers.length); // 3 ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-properties-of-array-instances-length | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Array`
Array.prototype.values() - JavaScript
Array.prototype.values() ======================== **`values()`** 方法會回傳一個包含陣列中的每一個索引之對應值(value)的新 **`Array Iterator`** 物件。 ```js var a = ["w", "y", "k", "o", "p"]; var iterator = a.values(); console.log(iterator.next().value); // w console.log(iterator.next().value); // y console.log(iterator.next().value); // k console.log(iterator.next().value); // o console.log(iterator.next().value); // p ``` 語法 -- ```js arr.values() ``` ### 回傳值 一個新的 `Array` 迭代器(iterator)物件。 範例 -- ### 使用 for...of 迴圈進行迭代 ```js var arr = ["w", "y", "k", "o", "p"]; var iterator = arr.values(); for (let letter of iterator) { console.log(letter); } ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-array.prototype.values | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Array.prototype.keys()` * `Array.prototype.entries()` * `Array.prototype.forEach()` (en-US) * `Array.prototype.every()` (en-US) * `Array.prototype.some()` (en-US)
Array.prototype.filter() - JavaScript
Array.prototype.filter() ======================== **`filter()`** 方法會建立一個經指定之函式運算後,由原陣列中通過該函式檢驗之元素所構成的新陣列。 嘗試一下 ---- ### ES6 版本 ```js const words = [ "spray", "limit", "elite", "exuberant", "destruction", "present", "happy", ]; let longWords = words.filter((word) => word.length > 6); // Filtered array longWords is ["exuberant", "destruction", "present"] ``` 語法 -- ``` var newArray = arr.filter(callback(element[, index[, array]])[, thisArg]) ``` ### 參數 `callback` 此函式為一個斷言,用於測試陣列中的每個元素。回傳值為 `true` 時將當前的元素保留至新陣列中,若為 `false` 則不保留。可傳入三個參數: `element` 原陣列目前所迭代處理中的元素。 `index`選擇性 原陣列目前所迭代處理中的元素之索引。 `array`選擇性 呼叫 `filter` 方法的陣列。 `thisArg` 選擇性 可選的。執行 `callback` 回呼函式的 `this` 值。 ### 回傳值 一個元素為通過回呼函式檢驗的新陣列。 描述 -- `filter()` 會將所有陣列中的元素分別傳入一次至 `callback` 函式當中,並將所有傳入此回呼函式並得到回傳值為 Truthy (en-US) 的元素建構成一個新的陣列。`callback` 函式只會於陣列目前迭代之索引有指派值時被呼叫,回呼函式不會在該陣列索引已被刪除或從未被賦值時被調用。原始陣列中沒有通過 `callback` 檢驗的元素會被簡單的跳過,且不會被包含在新建立的陣列中。 `callback` 函式於被調用時會傳入三個參數: 1. 元素值 2. 元素之索引 3. 被迭代的陣列物件 若有提供 `thisArg` 參數予 `filter` 方法,`thisArg` 將會被當作回呼函式的 `this` 值,否則 `this` 會是 `undefined`。`callback` 的最終 `this` 值是依據函式的 `this` 規則來決定。 `filter()` 不會修改呼叫它的原始陣列。 由 `filter()` 方法所回傳之新陣列的範圍,於 `callback` 函式第一次被調用之前就已經被設定。而在呼叫 `filter()` 之後才加至原始陣列中的元素,將不會傳入 `callback` 當中。假如原始陣列中元素的值改變或被刪除了,則 `callback` 得到此元素的值將會是 `filter()` 傳入元素當下的值。而被刪除的原始陣列元素並不會被迭代到。 範例 -- ### 過濾所有的小數字 以下範例會用 `filter()` 建立一個把所有小於 10 的元素都移掉的陣列。 ```js function isBigEnough(value) { return value >= 10; } var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); // filtered is [12, 130, 44] ``` ### 從 JSON 過濾無效的項目 以下範例會用 `filter()` 建立一個把非零 numeric `id` 的元素都過濾掉的的 JSON。 ```js var arr = [ { id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }, {}, { id: null }, { id: NaN }, { id: "undefined" }, ]; var invalidEntries = 0; function isNumber(obj) { return obj !== undefined && typeof obj === "number" && !isNaN(obj); } function filterByID(item) { if (isNumber(item.id)) { return true; } invalidEntries++; return false; } var arrByID = arr.filter(filterByID); console.log("過濾好的陣列\n", arrByID); // 過濾好的陣列 // [{ id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }] console.log("無效的元素數量 = ", invalidEntries); // 無效的元素數量 = 4 ``` ### 在陣列中搜尋 下面範例使用 `filter()` 去過濾符合搜尋條件的陣列內容。 ```js var fruits = ["apple", "banana", "grapes", "mango", "orange"]; /\*\* \* 陣列透過搜尋條件(查詢)過濾物件 \*/ function filterItems(query) { return fruits.filter(function (el) { return el.toLowerCase().indexOf(query.toLowerCase()) > -1; }); } console.log(filterItems("ap")); // ['apple', 'grapes'] console.log(filterItems("an")); // ['banana', 'mango', 'orange'] ``` ### ES2015 實作方式 ```js const fruits = ["apple", "banana", "grapes", "mango", "orange"]; /\*\* \* 陣列透過搜尋條件(查詢)過濾物件 \*/ const filterItems = (query) => { return fruits.filter( (el) => el.toLowerCase().indexOf(query.toLowerCase()) > -1, ); }; console.log(filterItems("ap")); // ['apple', 'grapes'] console.log(filterItems("an")); // ['banana', 'mango', 'orange'] ``` Polyfill -------- `filter()` 在 ECMA-262 第五版時被納入標準;它也許不會出現在該標準的所有實作引擎之中。你可以在你的腳本最前面加入下面的程式碼作為替代方案,讓不支援 `filter()` 的 ECMA-262 實作引擎能夠使用它。假設 `fn.call` 是採用 `Function.prototype.bind()` 的原始值,這個演算法完全和 ECMA-262 第五版定義的規格相同。 ```js if (!Array.prototype.filter) Array.prototype.filter = function (func, thisArg) { "use strict"; if (!(typeof func === "Function" && this)) throw new TypeError(); var len = this.length >>> 0, res = new Array(len), // 預先配置陣列 c = 0, i = -1; if (thisArg === undefined) while (++i !== len) // 確認物件的鍵值i是否有被設置 if (i in this) if (func(t[i], i, t)) res[c++] = t[i]; else while (++i !== len) // 確認物件的鍵值i是否有被設置 if (i in this) if (func.call(thisArg, t[i], i, t)) res[c++] = t[i]; res.length = c; // 將陣列縮至適當大小 return res; }; ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-array.prototype.filter | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Array.prototype.forEach()` (en-US) * `Array.prototype.every()` (en-US) * `Array.prototype.some()` (en-US) * `Array.prototype.reduce()`
Array.prototype.lastIndexOf() - JavaScript
Array.prototype.lastIndexOf() ============================= **`lastIndexOf()`** 方法會回傳給定元素於陣列中最後一個被找到之索引,若不存在於陣列中則回傳 -1。搜尋的方向為由陣列尾部向後(即向前)尋找,啟始於 `fromIndex`。 嘗試一下 ---- 語法 -- ``` arr.lastIndexOf(searchElement) arr.lastIndexOf(searchElement, fromIndex) ``` ### 參數 `searchElement` 欲在陣列中搜尋的元素。 `fromIndex` 選擇性 要由陣列尾部向後(即向前)搜尋的啟始索引。預設為陣列長度減一(`arr.length - 1`),即會搜尋整個陣列。假如索引大於等於陣列長度,會搜尋整個陣列。如果索引值為負數,會從陣列的最後一個往回算,最後一個的索引值為 -1,以此類推。注意:儘管往回算,但依然會從右往左全部搜尋。如果負數索引值在回頭計算之後仍然小於 0,將會回傳 -1,即不會搜尋陣列。 ### 回傳值 在陣列中找到的最後一個元素索引值;沒找到則為 **-1**。 描述 -- `lastIndexOf` compares `searchElement` to elements of the Array using strict equality (en-US) (the same method used by the ===, or triple-equals, operator). 範例 -- ### 使用 `lastIndexOf` The following example uses `lastIndexOf` to locate values in an array. ```js var numbers = [2, 5, 9, 2]; numbers.lastIndexOf(2); // 3 numbers.lastIndexOf(7); // -1 numbers.lastIndexOf(2, 3); // 3 numbers.lastIndexOf(2, 2); // 0 numbers.lastIndexOf(2, -2); // 0 numbers.lastIndexOf(2, -1); // 3 ``` ### 尋找該元素所有出現在陣列中的位置 The following example uses `lastIndexOf` to find all the indices of an element in a given array, using `push` to add them to another array as they are found. ```js var indices = []; var array = ["a", "b", "a", "c", "a", "d"]; var element = "a"; var idx = array.lastIndexOf(element); while (idx != -1) { indices.push(idx); idx = idx > 0 ? array.lastIndexOf(element, idx - 1) : -1; } console.log(indices); // [4, 2, 0] ``` Note that we have to handle the case `idx == 0` separately here because the element will always be found regardless of the `fromIndex` parameter if it is the first element of the array. This is different from the `indexOf` method. Polyfill -------- `lastIndexOf` was added to the ECMA-262 standard in the 5th edition; as such it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of `lastIndexOf` in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming `Object` (en-US), `TypeError` (en-US), `Number`, `Math.floor`, `Math.abs` (en-US), and `Math.min` (en-US) have their original values. ```js // Production steps of ECMA-262, Edition 5, 15.4.4.15 // Reference: http://es5.github.io/#x15.4.4.15 if (!Array.prototype.lastIndexOf) { Array.prototype.lastIndexOf = function (searchElement /\*, fromIndex\*/) { "use strict"; if (this === void 0 || this === null) { throw new TypeError(); } var n, k, t = Object(this), len = t.length >>> 0; if (len === 0) { return -1; } n = len - 1; if (arguments.length > 1) { n = Number(arguments[1]); if (n != n) { n = 0; } else if (n != 0 && n != 1 / 0 && n != -(1 / 0)) { n = (n > 0 || -1) \* Math.floor(Math.abs(n)); } } for (k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n); k >= 0; k--) { if (k in t && t[k] === searchElement) { return k; } } return -1; }; } ``` Again, note that this implementation aims for absolute compatibility with `lastIndexOf` in Firefox and the SpiderMonkey JavaScript engine, including in several cases which are arguably edge cases. If you intend to use this in real-world applications, you may be able to calculate `from` with less complicated code if you ignore those cases. 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-array.prototype.lastindexof | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 相容性備註 ----- * Starting with Firefox 47, this method will no longer return `-0`. For example, `[0].lastIndexOf(0, -0)` will now always return `+0` (Firefox bug 1242043). 參見 -- * `Array.prototype.indexOf()` * `TypedArray.prototype.lastIndexOf()` (en-US)
Array.prototype.copyWithin() - JavaScript
Array.prototype.copyWithin() ============================ **`copyWithin()`** 方法會對陣列的一部分進行淺拷貝至同一陣列的另一位置並回傳此陣列,而不修改其大小。 嘗試一下 ---- 語法 -- ``` arr.copyWithin(target) arr.copyWithin(target, start) arr.copyWithin(target, start, end) ``` ### 參數 `target` 要複製序列(sequence)至該位置的索引(起始為 0)。若為負數,`target` 將會自陣列末項開始計算。假如 `target` 大於等於 `arr.length`,則沒有項目會被複製。如果 `target` 的索引在 `start` 之後,則拷貝的序列將會被修剪以符合 `arr.length`。 `start` 選擇性 開始拷貝的起始元素索引(起始為 0)。若為負數,`start` 將會自陣列末項開始計算。如果省略 `start`,`copyWithin` 將會自陣列首項開始複製(預設為 0)。 `end` 選擇性 結束拷貝的結尾元素索引(起始為 0)。`copyWithin` 會拷貝至此索引,但不包含 `end`。若為負數,`end` 將會自陣列末項開始計算。如果省略 `end`,`copyWithin` 將會一路拷貝至陣列末項(預設至 `arr.length`)。 ### 回傳值 被修改後的陣列。 描述 -- The `copyWithin` works like C and C++'s `memmove`, and is a high-performance method to shift the data of an `Array`. This especially applies to the `TypedArray` (en-US) method of the same name. The sequence is copied and pasted as one operation; pasted sequence will have the copied values even when the copy and paste region overlap. The `copyWithin` function is intentionally *generic*, it does not require that its this value be an `Array` object. The `copyWithin` method is a mutable method. It does not alter the length of `this`, but will change its content and create new properties if necessary. 範例 -- ```js [1, 2, 3, 4, 5].copyWithin(-2); // [1, 2, 3, 1, 2] [1, 2, 3, 4, 5].copyWithin(0, 3); // [4, 5, 3, 4, 5] [1, 2, 3, 4, 5].copyWithin(0, 3, 4); // [4, 2, 3, 4, 5] [1, 2, 3, 4, 5].copyWithin(-2, -3, -1); // [1, 2, 3, 3, 4] [].copyWithin.call({ length: 5, 3: 1 }, 0, 3); // {0: 1, 3: 1, length: 5} // ES2015 Typed Arrays are subclasses of Array var i32a = new Int32Array([1, 2, 3, 4, 5]); i32a.copyWithin(0, 2); // Int32Array [3, 4, 5, 4, 5] // On platforms that are not yet ES2015 compliant: [].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4); // Int32Array [4, 2, 3, 4, 5] ``` Polyfill -------- ```js if (!Array.prototype.copyWithin) { Array.prototype.copyWithin = // Array: Number[, Number[, Number]] function copyWithin(target, start, stop) { var positiveT = target >= 0, positiveS = (start = start | 0) >= 0, length = this.length, zero = 0, r = function () { return (+new Date() \* Math.random()).toString(36); }, delimiter = "\b" + r() + "-" + r() + "-" + r() + "\b", hold; stop = stop || this.length; hold = this.slice .apply( this, positiveT ? [start, stop] : positiveS ? [start, -target] : [start], ) .join(delimiter); return ( this.splice.apply( this, positiveT ? [target, stop - start, hold] : positiveS ? [target, stop, hold] : [target, start, hold], ), this.join(delimiter).split(delimiter).slice(zero, length) ); }; } ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-array.prototype.copywithin | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Array`
Array.prototype.splice() - JavaScript
Array.prototype.splice() ======================== **`splice()`** 方法可以藉由刪除既有元素並/或加入新元素來改變一個陣列的內容。 嘗試一下 ---- 語法 -- ```js array.splice(start[, deleteCount[, item1[, item2[, ...]]]]) ``` ### 參數 `start` 陣列中要開始改動的元素索引(起始為 0)。若索引大於陣列長度,則實際開始的索引值會被設為陣列長度。若索引為負,則會從陣列中最後一個元素開始往前改動(起始為 -1)且若其絕對值大於陣列的長度,則會被設為 0。 `deleteCount` 選擇性 一個表示欲刪除的原陣列元素數量的整數。若省略了 `deleteCount`,或假如其值大於 `array.length - start`(也就是 `deleteCount` 大於 `start` 算起的剩餘元素數量),則所有從 `start` 開始到陣列中最後一個元素都會被刪除。若 `deleteCount` 為 0 或是負數,則不會有元素被刪除。 因此,你應該給定至少一個欲加入的新元素(見下方說明)。 `item1, item2, ...` 選擇性 從 `start` 開始,要加入到陣列的元素。 如果你沒有指定任何元素,則 `splice()` 只會依照 `start` 和 `deleteCount` 刪除陣列的元素。 ### 回傳值 一個包含被刪除的元素陣列。如果只有一個元素被刪除,依舊是回傳包含一個元素的陣列。 倘若沒有元素被刪除,則會回傳空陣列。 說明 -- 如果你插入的元素數量和刪除的數量不同,則回傳的陣列長度也會和原先的不同。 範例 -- ### 從索引 2 的位置開始,刪除 0 個元素並插入「drum」 ```js var myFish = ["angel", "clown", "mandarin", "sturgeon"]; var removed = myFish.splice(2, 0, "drum"); // myFish 為 ["angel", "clown", "drum", "mandarin", "sturgeon"] // removed 為 [], 沒有元素被刪除 ``` ### 從索引 3 的位置開始,刪除 1 個元素 ```js var myFish = ["angel", "clown", "drum", "mandarin", "sturgeon"]; var removed = myFish.splice(3, 1); // removed 為 ["mandarin"] // myFish 為 ["angel", "clown", "drum", "sturgeon"] ``` ### 從索引 2 的位置開始,刪除 1 個元素並插入「trumpet」 ```js var myFish = ["angel", "clown", "drum", "sturgeon"]; var removed = myFish.splice(2, 1, "trumpet"); // myFish 為 ["angel", "clown", "trumpet", "sturgeon"] // removed 為 ["drum"] ``` ### 從索引 0 的位置開始,刪除 2 個元素並插入「parrot」、「anemone」和「blue」 ```js var myFish = ["angel", "clown", "trumpet", "sturgeon"]; var removed = myFish.splice(0, 2, "parrot", "anemone", "blue"); // myFish 為 ["parrot", "anemone", "blue", "trumpet", "sturgeon"] // removed 為 ["angel", "clown"] ``` ### 從索引 2 的位置開始,刪除 2 個元素 ```js var myFish = ["parrot", "anemone", "blue", "trumpet", "sturgeon"]; var removed = myFish.splice(myFish.length - 3, 2); // myFish 為 ["parrot", "anemone", "sturgeon"] // removed 為 ["blue", "trumpet"] ``` ### 從索引 -2 的位置開始,刪除 1 個元素 ```js var myFish = ["angel", "clown", "mandarin", "sturgeon"]; var removed = myFish.splice(-2, 1); // myFish 為 ["angel", "clown", "sturgeon"] // removed 為 ["mandarin"] ``` ### 從索引 2 的位置開始,刪除所有元素(含索引 2) ```js var myFish = ["angel", "clown", "mandarin", "sturgeon"]; var removed = myFish.splice(2); // myFish 為 ["angel", "clown"] // removed 為 ["mandarin", "sturgeon"] ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-array.prototype.splice | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `push()` / `pop()` — add/remove elements from the end of the array * `unshift()` / `shift()` — add/remove elements from the beginning of the array * `concat()` — returns a new array comprised of this array joined with other array(s) and/or value(s)
Promise.prototype.catch() - JavaScript
Promise.prototype.catch() ========================= **catch()** 方法只處理 Promise 的被拒絕狀態,並回傳一個新的 `Promise` 物件。此方法的行為等同於呼叫 `Promise.prototype.then(undefined, onRejected)`。 語法 -- ```js p.catch(onRejected); p.catch(function (reason) { // rejection }); ``` ### 參數 onRejected 一個 `Function` (en-US) ,在 `Promise` 被拒絕時被呼叫。這個函式有一個引數: `reason` 失敗訊息。 若 onRejected 拋出一個錯誤或回傳一個被拒絕的 Promise,則 catch() 回傳的 Promise 被拒絕;其他情形都是被實現。 ### 回傳值 呼叫(`catch` 的 promise)物件,內部呼叫 `Promise.prototype.then`,傳入引數 undefined 及 onRejected;接著以之結果回傳(結果為 `Promise`)。 **內部呼叫演示:** ```js // overriding original Promise.prototype.then/catch just to add some logs (function (Promise) { var originalThen = Promise.prototype.then; var originalCatch = Promise.prototype.catch; Promise.prototype.then = function () { console.log( "> > > > > > called .then on %o with arguments: %o", this, arguments, ); return originalThen.apply(this, arguments); }; Promise.prototype.catch = function () { console.log( "> > > > > > called .catch on %o with arguments: %o", this, arguments, ); return originalCatch.apply(this, arguments); }; })(this.Promise); // calling catch on an already resolved promise Promise.resolve().catch(function XXX() {}); // logs: // > > > > > > called .catch on Promise{} with arguments: Arguments{1} [0: function XXX()] // > > > > > > called .then on Promise{} with arguments: Arguments{2} [0: undefined, 1: function XXX()] ``` 描述 -- `catch` 方法在處理 promise 組合的錯誤時很有幫助。 範例 -- ### 使用及串接 `catch` 方法 ```js var p1 = new Promise(function (resolve, reject) { resolve("Success"); }); p1.then(function (value) { console.log(value); // "Success!" throw "oh, no!"; }) .catch(function (e) { console.log(e); // "oh, no!" }) .then( function () { console.log("after a catch the chain is restored"); }, function () { console.log("Not fired due to the catch"); }, ); // The following behaves the same as above p1.then(function (value) { console.log(value); // "Success!" return Promise.reject("oh, no!"); }) .catch(function (e) { console.log(e); // "oh, no!" }) .then( function () { console.log("after a catch the chain is restored"); }, function () { console.log("Not fired due to the catch"); }, ); ``` ### 拋出例外時的陷阱 ```js // Throwing an error will call the catch method most of the time var p1 = new Promise(function (resolve, reject) { throw "Uh-oh!"; }); p1.catch(function (e) { console.log(e); // "Uh-oh!" }); // Errors thrown inside asynchronous functions will act like uncaught errors var p2 = new Promise(function (resolve, reject) { setTimeout(function () { throw "Uncaught Exception!"; }, 1000); }); p2.catch(function (e) { console.log(e); // This is never called }); // Errors thrown after resolve is called will be silenced var p3 = new Promise(function (resolve, reject) { resolve(); throw "Silenced Exception!"; }); p3.catch(function (e) { console.log(e); // This is never called }); ``` ### 如果 Promise 被實現 ```js //Create a promise which would not call onReject var p1 = Promise.resolve("calling next"); var p2 = p1.catch(function (reason) { //This is never called console.log("catch p1!"); console.log(reason); }); p2.then( function (value) { console.log("next promise's onFulfilled"); /\* next promise's onFulfilled \*/ console.log(value); /\* calling next \*/ }, function (reason) { console.log("next promise's onRejected"); console.log(reason); }, ); ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-promise.prototype.catch | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Promise` * `Promise.prototype.then()`
Promise.race() - JavaScript
Promise.race() ============== **`Promise.race(iterable)`** 方法回傳一個 promise 物件,此 promise 物件會於 iterable 引數中任一個 promise 轉為 resolve 或 rejected 時立即轉變成 resolve 或 rejected,並且接收其成功值或失敗訊息。 語法 -- ```js Promise.race(iterable); ``` ### 參數 iterable 一個 iterable 物件,像是 `Array`. 請參考可迭代協議。 ### 回傳值 當傳入的 iterable 中有 promise 被實現或拒絕時,立刻回傳被實現或拒絕的 `Promise`。 描述 -- `race` 函式回傳一個與傳入的 iterable 之中第一個被解決(settled)的 promise 相同方式被解決(且以相同值)的 `Promise`。 範例 -- ### `Promise.race` 的非同步性質 以下例子演示了 `Promise.race` 的非同步性質: ```js // we are passing as argument an array of promises that are already resolved, // to trigger Promise.race as soon as possible var resolvedPromisesArray = [Promise.resolve(33), Promise.resolve(44)]; var p = Promise.race(resolvedPromisesArray); // immediately logging the value of p console.log(p); // using setTimeout we can execute code after the stack is empty setTimeout(function () { console.log("the stack is now empty"); console.log(p); }); // logs, in order: // Promise { <state>: "pending" } // the stack is now empty // Promise { <state>: "fulfilled", <value>: 33 } ``` 一個空的 iterable 造成回傳的 promise 永久擱置: ```js var foreverPendingPromise = Promise.race([]); console.log(foreverPendingPromise); setTimeout(function () { console.log("the stack is now empty"); console.log(foreverPendingPromise); }); // logs, in order: // Promise { <state>: "pending" } // the stack is now empty // Promise { <state>: "pending" } ``` 若 iterable 中有一個或多個非 promise 值且/或一個已經被實現/解決的 promise,`Promise.race` 將以陣列中第一個這樣的值解決: ```js var foreverPendingPromise = Promise.race([]); var alreadyResolvedProm = Promise.resolve(666); var arr = [foreverPendingPromise, alreadyResolvedProm, "non-Promise value"]; var arr2 = [foreverPendingPromise, "non-Promise value", Promise.resolve(666)]; var p = Promise.race(arr); var p2 = Promise.race(arr2); console.log(p); console.log(p2); setTimeout(function () { console.log("the stack is now empty"); console.log(p); console.log(p2); }); // logs, in order: // Promise { <state>: "pending" } // Promise { <state>: "pending" } // the stack is now empty // Promise { <state>: "fulfilled", <value>: 666 } // Promise { <state>: "fulfilled", <value>: "non-Promise value" } ``` ### 使用 `Promise.race` 及 `setTimeout` 的範例 ```js var p1 = new Promise(function (resolve, reject) { setTimeout(resolve, 500, "one"); }); var p2 = new Promise(function (resolve, reject) { setTimeout(resolve, 100, "two"); }); Promise.race([p1, p2]).then(function (value) { console.log(value); // "two" // Both resolve, but p2 is faster }); var p3 = new Promise(function (resolve, reject) { setTimeout(resolve, 100, "three"); }); var p4 = new Promise(function (resolve, reject) { setTimeout(reject, 500, "four"); }); Promise.race([p3, p4]).then( function (value) { console.log(value); // "three" // p3 is faster, so it resolves }, function (reason) { // Not called }, ); var p5 = new Promise(function (resolve, reject) { setTimeout(resolve, 500, "five"); }); var p6 = new Promise(function (resolve, reject) { setTimeout(reject, 100, "six"); }); Promise.race([p5, p6]).then( function (value) { // Not called }, function (reason) { console.log(reason); // "six" // p6 is faster, so it rejects }, ); ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-promise.race | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Promise` * `Promise.all()`
Promise.resolve() - JavaScript
Promise.resolve() ================= **`Promise.resolve(value)`** 方法回傳一個以 value 判定結果的 `Promise` 物件。若 value 是個 thenable(例如,具有 `then()` 方法,則回傳的 promise 將依其結果採取其最終狀態;若 value 是 promise,則作為呼叫 Promise.resolve 之結果;其他情形都將回傳以 value 實現的 promise。 語法 -- ```js Promise.resolve(value); Promise.resolve(promise); Promise.resolve(thenable); ``` ### 參數 value 將被 `Promise` 實現的引數(argument)。可以是個 `Promise` 或待解決的 thenable。 ### 回傳值 以 value 或作為 value 的 promise 解決的 `Promise`。 描述 -- `靜態函式` `Promise.resolve` 回傳判定後的 `Promise。` 範例 -- ### 使用 `Promise.resolve` 靜態方法 ```js Promise.resolve("Success").then( function (value) { console.log(value); // "Success" }, function (value) { // not called }, ); ``` ### 判定陣列 ```js var p = Promise.resolve([1, 2, 3]); p.then(function (v) { console.log(v[0]); // 1 }); ``` ### 判定另一個 `Promise` ```js var original = Promise.resolve(33); var cast = Promise.resolve(original); cast.then(function (value) { console.log("value: " + value); }); console.log("original === cast ? " + (original === cast)); // logs, in order: // original === cast ? true // value: 33 ``` 由於 handler 是非同步地被調用而導致相反的紀錄順序。經由這篇文章了解 then 如何運作。 ### 判定 thenable 及拋出 Error ```js // Resolving a thenable object var p1 = Promise.resolve({ then: function (onFulfill, onReject) { onFulfill("fulfilled!"); }, }); console.log(p1 instanceof Promise); // true, object casted to a Promise p1.then( function (v) { console.log(v); // "fulfilled!" }, function (e) { // not called }, ); // Thenable throws before callback // Promise rejects var thenable = { then: function (resolve) { throw new TypeError("Throwing"); resolve("Resolving"); }, }; var p2 = Promise.resolve(thenable); p2.then( function (v) { // not called }, function (e) { console.log(e); // TypeError: Throwing }, ); // Thenable throws after callback // Promise resolves var thenable = { then: function (resolve) { resolve("Resolving"); throw new TypeError("Throwing"); }, }; var p3 = Promise.resolve(thenable); p3.then( function (v) { console.log(v); // "Resolving" }, function (e) { // not called }, ); ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-promise.resolve | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Promise`
Promise.prototype.finally() - JavaScript
Promise.prototype.finally() =========================== **`finally()`** 方法會回傳一個 `Promise`。當 promise 被 settled 後,無論其結果是 fulfilled 還是 rejected ,都會執行指定的回呼函數。它提供了一個讓 `Promise` 在被確認後,無論是 fulfilled 或是 rejected 都會執行某些程式碼的一種手段。 這樣可以避免你在 promise 的 `then()` 和 `catch()` 重複處理相同的程式碼。 Syntax ------ ```js p.finally(onFinally); p.finally(function () { // settled(fulfilled 或 rejected) }); ``` ### Parameters `onFinally` 當 `Promise` settled 後呼叫的 `Function` (en-US)。 ### Return value 回傳 `Promise` 當 `finally` 的處理函數 `onFinally` 被指定時。 Description ----------- 當你希望在 promise settled 後且不關心它的結果為何時,執行一些處理或清理的工作, `finally()` 方法會很有幫助。 `finally()` 方法非常類似於 `.then(onFinally, onFinally)` 的呼叫方式,但仍有一些差異: * 當建立行內的函數時,可以只傳遞一次,從而避免重複宣告或為它宣告變數。 * `finally` 的回呼函數並不會接收到任何引數,因其沒有可靠的方式來確認 promise 是被 fulfilled 還是 rejected 。它的使用情境僅適用於當你*不關心* rejection 的原因或 fulfillment 的值,因此無須提供。範例: + 與 `Promise.resolve(2).then(() => {}, () => {})`(將被 resolved 為`undefined`)不同,`Promise.resolve(2).finally(() => {})` 將被 resolved 為`2`。 + 同樣的,與 `Promise.reject(3).then(() => {}, () => {})`(將 fulfilled 為`undefined`)不同,`Promise.reject(3).finally(() => {})` 將被 rejected 為`3`。 **備註:** 在 finally 回呼中使用 throw(或回傳 rejected promise)會導致新的 promise 被 reject,reject 的原因則是呼叫 throw() 時所指定的值。 範例 -- ```js let isLoading = true; fetch(myRequest) .then(function (response) { var contentType = response.headers.get("content-type"); if (contentType && contentType.includes("application/json")) { return response.json(); } throw new TypeError("Oops, we haven't got JSON!"); }) .then(function (json) { /\* process your JSON further \*/ }) .catch(function (error) { console.log(error); }) .finally(function () { isLoading = false; }); ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-promise.prototype.finally | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Promise` * `Promise.prototype.then()` * `Promise.prototype.catch()`
Promise.prototype.then() - JavaScript
Promise.prototype.then() ======================== **`then()`** 方法回傳一個 `Promise` (en-US) 物件。它接收兩個引數: `Promise` 在成功及失敗情況時的回呼函式。 **備註:** 如果有一個或兩個引數被省略,或為非函式(non-functions),則 `then` 將處於遺失 handler(s) 的狀態,但不會產生錯誤。若發起 `then` 之 `Promise` 採取了一個狀態(實現(`fulfillment)`或拒絕(`rejection))`而 `then` 沒有處理它的函式,一個不具有額外 handlers 的新 `Promise` 物件將被建立,單純採取原 `Promise` 其最終狀態。 語法 -- ```js p.then(onFulfilled[, onRejected]); p.then(function(value) { // fulfillment }, function(reason) { // rejection }); ``` ### 參數 `onFulfilled` 一個 `Function` (en-US),當 `Promise` 被實現(fulfilled)時被呼叫。此函式接收一個實現值(`fulfillment value`)作為引數。 `onRejected` 選擇性 一個 `Function` (en-US),當 `Promise` 被拒絕(rejected)時被呼叫。此函式接收一個失敗訊息(`rejection reason`)作為引數。 ### 回傳值 一個進入**擱置**(pending)狀態的 `Promise`。(只要堆疊一空)handler 函式**非同步地**(asynchronously)被呼叫。在調用 handler 後,若 handler 函式: * 回傳一個值,則 `then` 回傳之 promise 以此值被實現(resolved)。 * 拋出一個例外,則 `then` 回傳之 promise 以此例外被否決(rejected)。 * 回傳一個被實現的 promise,則 `then` 回傳之 promise 以此值被實現。 * 回傳一個被否決的 promise,則 `then` 回傳之 promise 以此值被否決。 * 回傳另一個被**擱置**的 promise 物件,則 `then` 回傳之 promise 之實現/拒絕隨後由處理函式之實現/否決決定。並且,`then` 回傳之 promise 將與處理函式回傳之 promise 以相同值被解決。 以下例子展示 `then` 方法的非同步性質(asynchronicity)。 ```js // 使用一個已實現的 promise,'then' 區塊將立即被觸發,但是它的 handlers 將是非同步地被觸發,如同 console.logs 所示 var resolvedProm = Promise.resolve(33); var thenProm = resolvedProm.then(function (value) { console.log("我在 main stack 之後被呼叫。收到及將回傳的值為:" + value); return value; }); // 立即紀錄 thenProm console.log(thenProm); // 我們可以使用 setTimeout 以延遲(postpone)函式執行直到堆疊為空 setTimeout(function () { console.log(thenProm); }); // 紀錄結果,依序為: // Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined} // "我在 main stack 之後被呼叫。收到及將回傳的值為:33" // Promise {[[PromiseStatus]]: "resolved", [[PromiseValue]]: 33} ``` 描述 -- 因為 `then` 和 `Promise.prototype.catch()` 方法都回傳 promises,它們可以被串接 — 稱為組合(*composition)。* 範例 -- ### 運用 `then` 方法 ```js var p1 = new Promise((resolve, reject) => { resolve("Success!"); // or // reject ("Error!"); }); p1.then( (value) => { console.log(value); // Success! }, (reason) => { console.log(reason); // Error! }, ); ``` ### 串接 `then` 方法回傳一個 `Promise` 而可以進行方法串接(method chaining)。 如果傳入 `then` 的 handler 函式回傳一個 promise,一個等價的 `Promise` 將被展現給方法串接中的下一個 then 。以下程式碼片段透過 `setTimout` 函式模擬非同步程式碼。 ```js Promise.resolve("foo") // 1. Receive "foo" concatenate "bar" to it and resolve that to the next then .then(function (string) { return new Promise(function (resolve, reject) { setTimeout(function () { string += "bar"; resolve(string); }, 1); }); }) // 2. receive "foobar", register a callback function to work on that string // and print it to the console, but not before return the unworked on // string to the next then .then(function (string) { setTimeout(function () { string += "baz"; console.log(string); }, 1); return string; }) // 3. print helpful messages about how the code in this section will be run // before string is actually processed by the mocked asynchronous code in the // prior then block. .then(function (string) { console.log( "Last Then: oops... didn't bother to instantiate and return " + "a promise in the prior then so the sequence may be a bit " + "surprising", ); // Note that `string` will not have the 'baz' bit of it at this point. This // is because we mocked that to happen asynchronously with a setTimeout function console.log(string); }); ``` 當 handler 僅回傳一個值,實際上它將回傳 `Promise.resolve(<value returned by whichever handler was called>)`. ```js var p2 = new Promise(function (resolve, reject) { resolve(1); }); p2.then(function (value) { console.log(value); // 1 return value + 1; }).then(function (value) { console.log(value + "- This synchronous usage is virtually pointless"); // 2- This synchronous usage is virtually pointless }); p2.then(function (value) { console.log(value); // 1 }); ``` 若函式拋出一個錯誤或回傳一個被否決的 Promise,`then` 也將回傳一個被否決的 Promise。 ```js Promise.resolve() .then(() => { // 使 .then() 回傳一個被否決的 Promise throw "Oh no!"; }) .then( () => { console.log("Not called."); }, (reason) => { console.error("onRejected function called: ", reason); }, ); ``` 在所有其他情形,實現中的 Promise 被回傳。在以下例子中,第一個 `then()` 將回傳一個實現中包裹 42 的 promise,即使串接中的前一個 Promise 被否決。 ```js Promise.reject() .then( () => 99, () => 42, ) // onRejected returns 42 which is wrapped in a resolving Promise .then((solution) => console.log("Resolved with " + solution)); // Resolved with 42 ``` 實務上,使用 `catch` 捕捉被否決的 promise 較理想的,而不建議使用兩個引數 `then` 語法,如下展示。 ```js Promise.resolve() .then(() => { // Makes .then() return a rejected promise throw "Oh no!"; }) .catch((reason) => { console.error("onRejected function called: ", reason); }) .then(() => { console.log("I am always called even if the prior then's promise rejects"); }); ``` 你也可以透過串接實作一個 Promise-based API 函式,基於它本身。 ```js function fetch\_current\_data() { // The fetch() API returns a Promise. This function // exposes a similar API, except the fulfillment // value of this function's Promise has had more // work done on it. return fetch("current-data.json").then((response) => { if (response.headers.get("content-type") != "application/json") { throw new TypeError(); } var j = response.json(); // maybe do something with j return j; // fulfillment value given to user of // fetch\_current\_data().then() }); } ``` 若 `onFulfilled` 回傳一個 promise,則 `then` 的實現/否決將取決它。 ```js function resolveLater(resolve, reject) { setTimeout(function () { resolve(10); }, 1000); } function rejectLater(resolve, reject) { setTimeout(function () { reject(20); }, 1000); } var p1 = Promise.resolve("foo"); var p2 = p1.then(function () { // Return promise here, that will be resolved to 10 after 1 second return new Promise(resolveLater); }); p2.then( function (v) { console.log("resolved", v); // "resolved", 10 }, function (e) { // not called console.log("rejected", e); }, ); var p3 = p1.then(function () { // Return promise here, that will be rejected with 20 after 1 second return new Promise(rejectLater); }); p3.then( function (v) { // not called console.log("resolved", v); }, function (e) { console.log("rejected", e); // "rejected", 20 }, ); ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-promise.prototype.then | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Promise` * `Promise.prototype.catch()`
Promise.reject() - JavaScript
Promise.reject() ================ **`Promise.reject(reason)`** 方法回傳一個以 `reason` 拒絕的 `Promise` 物件。 語法 -- ```js Promise.reject(reason); ``` ### 參數 reason `Promise` 的失敗訊息。 ### 回傳值 一個以 `reason` 拒絕的 `Promise`。 描述 -- 靜態函式 `Promise.reject` 回傳一個被拒絕的 `Promise。由於除錯目的及選擇性錯誤捕捉(selective error catching),使`用一個 `instanceof` `Error` (en-US) 作為 reason 是很有幫助的。 範例 -- ### 使用靜態方法 Promise.reject() ```js Promise.reject(new Error("fail")).then( function (error) { // not called }, function (error) { console.log(error); // Stacktrace }, ); ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-promise.reject | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Promise` * Selective error catching using the BlueBird Promise library
Promise.all() - JavaScript
Promise.all() ============= **`Promise.all()`** 方法回傳一個 `Promise` 物件,當引數 `iterable` 中所有的 promises 都被實現(resolved),或引數 iterable 不含任何 promise 時,被實現。或以第一個被拒絕的 promise 的原因被拒絕。 語法 -- ```js Promise.all(iterable); ``` iterable 一個 iterable 物件像是 `Array` 或 `String`。 ### 回傳值 * 一個\*\*已被實現(already resolved)\*\*的 `Promise`,若傳入的 iterable 為空。 * 一個**非同步地被實現(asynchronously resolved)**的 `Promise` 若傳入的 iterable 不含 promise。注意,Google Chrome 58 對此情形回傳一個**已被解決**的 promise。 * 一個**擱置(pending)**的 `Promise`,對所有剩餘情形。此 promise 接著被**非同步地**被 resolved/rejected(只要堆疊為空)當 iterable 中所有的 promises 都被實現,或其中一個被拒絕。參見下方關於"Promise.all 的非同步與同步性質"的例子。 描述 -- 此方法在聚集(aggregating)多個 promises 的結果時很有幫助。 實現(Fulfillment): 若傳入空的 iterable,此方法(同步地)回傳一個已被解決的 promise。若所有傳入的 promises 都被實現,或都不是 promise,`Promise.all` 回傳的 promise 被非同步地實現。無論是哪個情形,回傳一個以 iterable 其內**所有**值(包含非 promise 值)作為引數的陣列被實現。 拒絕(Rejection): 若任一個傳入的 promise 被拒絕,Promise.all 非同步地以其值被拒絕,無論其他 promises 是否被解決。 範例 -- ### 使用 `Promise.all` `Promise.all` 等到全部實現(或一個拒絕)。 ```js var p1 = Promise.resolve(3); var p2 = 1337; var p3 = new Promise((resolve, reject) => { setTimeout(resolve, 100, "foo"); }); Promise.all([p1, p2, p3]).then((values) => { console.log(values); // [3, 1337, "foo"] }); ``` 若 iterable 含非 promise 值,它們將被忽略,但依然會被記入回傳 promise 陣列值(若被實現): ```js // this will be counted as if the iterable passed is empty, so it gets fulfilled var p = Promise.all([1, 2, 3]); // this will be counted as if the iterable passed contains only the resolved promise with value "444", so it gets fulfilled var p2 = Promise.all([1, 2, 3, Promise.resolve(444)]); // this will be counted as if the iterable passed contains only the rejected promise with value "555", so it gets rejected var p3 = Promise.all([1, 2, 3, Promise.reject(555)]); // using setTimeout we can execute code after the stack is empty setTimeout(function () { console.log(p); console.log(p2); console.log(p3); }); // logs // Promise { <state>: "fulfilled", <value>: Array[3] } // Promise { <state>: "fulfilled", <value>: Array[4] } // Promise { <state>: "rejected", <reason>: 555 } ``` ### `Promise.all` 的非同步與同步性質 以下例子驗證了 `Promise.all` 的非同步性質(asynchronicity)(或同步性質(synchronicity),若傳入的 iterable 是空的): ```js // we are passing as argument an array of promises that are already resolved, // to trigger Promise.all as soon as possible var resolvedPromisesArray = [Promise.resolve(33), Promise.resolve(44)]; var p = Promise.all(resolvedPromisesArray); // immediately logging the value of p console.log(p); // using setTimeout we can execute code after the stack is empty setTimeout(function () { console.log("the stack is now empty"); console.log(p); }); // logs, in order: // Promise { <state>: "pending" } // the stack is now empty // Promise { <state>: "fulfilled", <value>: Array[2] } ``` `當` `Promise.all` 被拒絕時發生一樣的事情: ```js var mixedPromisesArray = [Promise.resolve(33), Promise.reject(44)]; var p = Promise.all(mixedPromisesArray); console.log(p); setTimeout(function () { console.log("the stack is now empty"); console.log(p); }); // logs // Promise { <state>: "pending" } // the stack is now empty // Promise { <state>: "rejected", <reason>: 44 } ``` 注意!`Promise.all` 同步地被解決**若且唯若**傳入的 iterable 為空: ```js var p = Promise.all([]); // will be immediately resolved var p2 = Promise.all([1337, "hi"]); // non-promise values will be ignored, but the evaluation will be done asynchronously console.log(p); console.log(p2); setTimeout(function () { console.log("the stack is now empty"); console.log(p2); }); // logs // Promise { <state>: "fulfilled", <value>: Array[0] } // Promise { <state>: "pending" } // the stack is now empty // Promise { <state>: "fulfilled", <value>: Array[2] } ``` ### `Promise.all` 的失敗優先(fail-fast)行為 `當任一個陣列成員被拒絕則` `Promise.all` 被拒絕。例如,若傳入四個將在一段時間後被解決的 promises,而其中一個立刻被拒絕,則 `Promise.all` 將立刻被拒絕。 ```js var p1 = new Promise((resolve, reject) => { setTimeout(resolve, 1000, "one"); }); var p2 = new Promise((resolve, reject) => { setTimeout(resolve, 2000, "two"); }); var p3 = new Promise((resolve, reject) => { setTimeout(resolve, 3000, "three"); }); var p4 = new Promise((resolve, reject) => { setTimeout(resolve, 4000, "four"); }); var p5 = new Promise((resolve, reject) => { reject("reject"); }); Promise.all([p1, p2, p3, p4, p5]).then( (values) => { console.log(values); }, (reason) => { console.log(reason); }, ); //From console: //"reject" //You can also use .catch Promise.all([p1, p2, p3, p4, p5]) .then((values) => { console.log(values); }) .catch((reason) => { console.log(reason); }); //From console: //"reject" ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-promise.all | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Promise` * `Promise.race()`
Function.prototype.call - JavaScript
Function.prototype.call ======================= 使用給定的 `this` 參數以及分別給定的參數來呼叫某個函數 **備註:** 此函數的所有語法大致上與 `apply()` (en-US) 相同,他們基本上不同處只有 `call()` 接受一連串的參數,而 `apply()` 單一的 array 作為參數 | Function (en-US)物件的方法 | | --- | | 被實作於 | JavaScript 1.3 | | ECMAScript 版本 | ECMAScript 第三版 | 語法 -- ```js fun.call(thisArg[, arg1[, arg2[, ...]]]) ``` ### 參數 `thisArg` 呼叫\*`fun`\*時提供的`this`值。 注意,它可能是一個無法在函數內看到的值:若這個函數是在非嚴苛模式( non-strict mode (en-US) ), `null` `、undefined` 將會被置換成全域變數,而原生型態的值將會被封裝 `arg1, arg2, ...` 其他參數 描述 -- 你可以在呼叫一個現存的函數時,使用不一樣的 `this` 物件。`this` 會參照到目前的物件,呼叫的物件上 使用 `call`,你可以實作函數一次,然後在其他的物件上直接繼承它,而不用在新的物件上重寫該函數 範例 -- ### 使用 `call` 來串接物件上的建構子 你可以使用 `call` 來串接其他物件的建構子,就像 Java。下面的例子中,`Product` 物件的建構子定義了兩個參數 `name` 以及 `price`。其他函數 `Food` 及 `Toy` 引用了 `Product` 並傳入 `this`、`name` 和 `price`。Product 初始化它的屬性 `name` 和 `price`,而兩個子函數則定義了 `category`。 ```js function Product(name, price) { this.name = name; this.price = price; if (price < 0) throw RangeError( 'Cannot create product "' + name + '" with a negative price', ); return this; } function Food(name, price) { Product.call(this, name, price); this.category = "food"; } Food.prototype = new Product(); function Toy(name, price) { Product.call(this, name, price); this.category = "toy"; } Toy.prototype = new Product(); var cheese = new Food("feta", 5); var fun = new Toy("robot", 40); ``` ### 使用 `call` 來呼叫匿名的函數 下面這個簡易的例子中,我們做了一個匿名的函數,並用 `call` 來讓它應用在每個在串列中的物件中. 這個匿名函數的主要用途是加入一個 print 函數到每個物件上,這個函數可以印出每個物件的 index 指標。 傳入物件作為 `this` 的值並不是必要的,但他有解釋的用途。 ```js var animals = [ { species: "Lion", name: "King" }, { species: "Whale", name: "Fail" }, ]; for (var i = 0; i < animals.length; i++) { (function (i) { this.print = function () { console.log("#" + i + " " + this.species + ": " + this.name); }; this.print(); }).call(animals[i], i); } ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-function.prototype.call | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * apply (en-US)
Function.prototype.apply() - JavaScript
Function.prototype.apply() ========================== `apply()` 方法會呼叫一個以 this 的代表值和一個陣列形式的值組(或是一個 array-like object (en-US))為參數的函式。 **備註:** 這個函式的語法和 `call()` 幾乎一樣,最大的不同是 `call()` 接受**一連串的參數**,而 `apply()` 接受一組陣列形式的參數。 語法 -- ```js fun.apply(thisArg, [argsArray]) ``` ### 參數 `thisArg` 讓 *`fun`* 呼叫時可以視為 this 的值。注意,這可能並不是最後會在方法裡看見的值:如果這是一個在非 non-strict mode 下運作的程式碼,`null` (en-US) 及 `undefined` (en-US) 將會被全域物件取代,而原始類別將被封裝。 `argsArray` 一個 array-like 物件 ,定義了 *`fun`* 要呼叫的一組參數,如果沒有需要提供,可以傳入 `null` (en-US) 或 `undefined` (en-US)。從 ECMAScript 5 開始,這些參數不僅可以是泛型的 array-like 物件,而不一定要是一組陣列。查看下方的瀏覽器相容性資訊。 ### 回傳值 傳入 `this` 值及一組參數後得到的結果。 描述 -- 在呼叫一個現存的函式時,你可以傳入不同的 `this` 物件值。this 參考到現在的物件,也就是正在執行的物件。apply 讓你可以只寫一次方法後,讓其他物件也繼承到這個方法,而不用一再重寫。 `apply` 與 `call()` 非常相似,不同的是支援的傳入參數類型。使用陣列形式的參數,而不是命名過的接收參數。使用 `apply` 時,你可以選擇使用陣列實字:`fun.apply(this, ['eat', 'bananas']);` 或是 `Array` 物件:`fun.apply(this, new Array('eat', 'bananas'))`。 除此之外,你也可以使用 `arguments` (en-US) 代表 `argsArray` 參數。arguments 是在函式裡的區域變數,可用來存取所有沒有特別被所呼叫物件指定的傳入參數。因此,使用 apply 時你不需要知道所呼叫函式的指定參數。使用 `arguments` 把所有參數傳入呼叫的方法裡,而被呼叫的方法會接手處理這些參數。 從 ECMAScript 5th 版本後,也可以使用陣列形式的物件,在實踐上這代表他會擁有 `length` 以及整數範圍 `(0...length-1)` 的屬性。舉例來說,你可以使用 `NodeList` 或是一個像這樣的自定義屬性:`{ 'length': 2, '0': 'eat', '1': 'bananas' }`。 **備註:** 一般瀏覽器,包括 Chrome 14 及 Internet Explorer 9,仍不支援陣列形式的物件,所以會對此丟出一個錯誤。 範例 -- ### 使用 `apply` 與建構子鏈結 你可以使用 `apply` 鏈結 constructors 一個物件,與 Java 相似,如下範例中我們可以建立一個全域的 `Function` (en-US) 方法叫 `construct`,使你可以使用類陣列的物件與建構子去替代參數列表。 ```js Function.prototype.construct = function (aArgs) { var oNew = Object.create(this.prototype); this.apply(oNew, aArgs); return oNew; }; ``` **備註:** 如上範例的 `Object.create()` 方法是屬於比較新的寫法。如需使用閉包的替代方法,請參考以下的範例: ```js Function.prototype.construct = function (aArgs) { var fConstructor = this, fNewConstr = function () { fConstructor.apply(this, aArgs); }; fNewConstr.prototype = fConstructor.prototype; return new fNewConstr(); }; ``` 使用範例: ```js function MyConstructor() { for (var nProp = 0; nProp < arguments.length; nProp++) { this["property" + nProp] = arguments[nProp]; } } var myArray = [4, "Hello world!", false]; var myInstance = MyConstructor.construct(myArray); console.log(myInstance.property1); // logs 'Hello world!' console.log(myInstance instanceof MyConstructor); // logs 'true' console.log(myInstance.constructor); // logs 'MyConstructor' ``` **備註:** This non-native `Function.construct` method will not work with some native constructors (like `Date`, for example). In these cases you have to use the `Function.prototype.bind` method (for example, imagine having an array like the following, to be used with `Date` constructor: `[2012, 11, 4]`; in this case you have to write something like: `new (Function.prototype.bind.apply(Date, [null].concat([2012, 11, 4])))()` — anyhow this is not the best way to do things and probably should not be used in any production environment). ### 使用 `apply` 於內建的函數 apply 可以巧妙的在某些任務中使用內建函數,否則可能會循環遍歷整個陣列來寫入。如下範例,我們使用 `Math.max/Math.min` 來找出陣列中最大/最小的值。 ```js // min/max number in an array var numbers = [5, 6, 2, 3, 7]; // using Math.min/Math.max apply var max = Math.max.apply(null, numbers); // This about equal to Math.max(numbers[0], ...) // or Math.max(5, 6, ...) var min = Math.min.apply(null, numbers); // vs. simple loop based algorithm (max = -Infinity), (min = +Infinity); for (var i = 0; i < numbers.length; i++) { if (numbers[i] > max) { max = numbers[i]; } if (numbers[i] < min) { min = numbers[i]; } } ``` But beware: in using `apply` this way, you run the risk of exceeding the JavaScript engine's argument length limit. The consequences of applying a function with too many arguments (think more than tens of thousands of arguments) vary across engines (JavaScriptCore has hard-coded argument limit of 65536), because the limit (indeed even the nature of any excessively-large-stack behavior) is unspecified. Some engines will throw an exception. More perniciously, others will arbitrarily limit the number of arguments actually passed to the applied function. (To illustrate this latter case: if such an engine had a limit of four arguments [actual limits are of course significantly higher], it would be as if the arguments `5, 6, 2, 3` had been passed to `apply` in the examples above, rather than the full array.) If your value array might grow into the tens of thousands, use a hybrid strategy: apply your function to chunks of the array at a time: ```js function minOfArray(arr) { var min = Infinity; var QUANTUM = 32768; for (var i = 0, len = arr.length; i < len; i += QUANTUM) { var submin = Math.min.apply(null, arr.slice(i, Math.min(i + QUANTUM, len))); min = Math.min(submin, min); } return min; } var min = minOfArray([5, 6, 2, 3, 7]); ``` ### Using apply in "monkey-patching" Apply can be the best way to monkey-patch a built-in function of Firefox, or JS libraries. Given `someobject.foo` function, you can modify the function in a somewhat hacky way, like so: ```js var originalfoo = someobject.foo; someobject.foo = function () { // Do stuff before calling function console.log(arguments); // Call the function as it would have been called normally: originalfoo.apply(this, arguments); // Run stuff after, here. }; ``` This method is especially handy where you want to debug events, or interface with something that has no API like the various `.on([event]...` events, such as those usable on the Devtools Inspector). 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-function.prototype.apply | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `arguments` (en-US) object * `Function.prototype.bind()` * `Function.prototype.call()` * Functions and function scope (en-US) * `Reflect.apply()` (en-US)
Function.length - JavaScript
Function.length =============== **`length`** property 表示該 function 預期被傳入的參數數量 | `Function.length` 的屬性特性 | | --- | | 可寫 | 否 | | 可列舉 | 否 | | 可配置 | 是 | 描述 -- `length` 是 function 物件的一個 property,表示該 function 預期被傳入的參數數量,這個數量並不包含 rest parameter (en-US) 且只包涵第一個預設參數(Default Parameters)前的參數。相較之下 `arguments.length` (en-US) 是 function 內部的物件,會提供真正傳進 function 中的參數數量。 ### `Function` 建構子的 data property `Function` (en-US) 建構子本身就是一個 `Function` (en-US) 物件。其 `length` data property 的值為 1。此 property 的 attributes 包含: Writable: `false`, Enumerable: `false`, Configurable: `true`. ### `Function` prototype 物件的 property `Function` (en-US) prototype 物件的 length property 其值為 0。 範例 -- ```js console.log(Function.length); /\* 1 \*/ console.log(function () {}.length); /\* 0 \*/ console.log(function (a) {}.length); /\* 1 \*/ console.log(function (a, b) {}.length); /\* 2 以此類推. \*/ console.log(function (...args) {}.length); /\* 0, rest parameter 不包含在內 \*/ console.log(function (a, b = 1, c) {}.length); /\* 1 \*/ // 只有在預設參數前的參數會被算到,也就是只有 a 會被視為必須傳入的參數 // 而 c 將被預設為 undefined ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-function-instances-length | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Function` (en-US)
Function.prototype.bind() - JavaScript
Function.prototype.bind() ========================= **`bind()`** 方法,會建立一個新函式。該函式被呼叫時,會將 `this` 關鍵字設為給定的參數,並在呼叫時,帶有提供之前,給定順序的參數。 語法 -- ```js fun.bind(thisArg[, arg1[, arg2[, ...]]]) ``` ### 參數 `thisArg` The value to be passed as the `this` parameter to the target function when the bound function is called. The value is ignored if the bound function is constructed using the `new` operator. `arg1, arg2, ...` Arguments to prepend to arguments provided to the bound function when invoking the target function. ### 回傳值 A copy of the given function with the specified **`this`** value and initial arguments. 敘述 -- **bind()** 函式建立了一個新的**綁定函式(BF)**。**BF** 是個包裝了原有函式物件的 **exotic function object**(**ECMAScript 2015** 的術語)。通常,呼叫 **BF** 會執行該 **wrapped function**。**BF** 含有以下內部屬性: * **[[BoundTargetFunction]]** - the wrapped function object; * **[[BoundThis]]** - the value that is always passed as **this** value when calling the wrapped function. * **[[BoundArguments]]** - a list of values whose elements are used as the first arguments to any call to the wrapped function. * **[[Call]]** - executes code associated with this object. Invoked via a function call expression. The arguments to the internal method are a **this** value and a list containing the arguments passed to the function by a call expression. When bound function is called, it calls internal method **[[Call]]** on **[[BoundTargetFunction]],** with following arguments **Call(*boundThis*, *args*).** Where, ***boundThis*** is **[[BoundThis]]**, **args** is **[[BoundArguments]]** followed by the arguments passed by the function call. A bound function may also be constructed using the `new` operator: doing so acts as though the target function had instead been constructed. The provided **`this`** value is ignored, while prepended arguments are provided to the emulated function. 範例 -- ### 建立綁定函式 The simplest use of `bind()` is to make a function that, no matter how it is called, is called with a particular **`this`** value. A common mistake for new JavaScript programmers is to extract a method from an object, then to later call that function and expect it to use the original object as its `this` (e.g. by using that method in callback-based code). Without special care, however, the original object is usually lost. Creating a bound function from the function, using the original object, neatly solves this problem: ```js this.x = 9; // this refers to global "window" object here in the browser var module = { x: 81, getX: function () { return this.x; }, }; module.getX(); // 81 var retrieveX = module.getX; retrieveX(); // returns 9 - The function gets invoked at the global scope // Create a new function with 'this' bound to module // New programmers might confuse the // global var x with module's property x var boundGetX = retrieveX.bind(module); boundGetX(); // 81 ``` ### Partially applied functions The next simplest use of `bind()` is to make a function with pre-specified initial arguments. These arguments (if any) follow the provided `this` value and are then inserted at the start of the arguments passed to the target function, followed by the arguments passed to the bound function, whenever the bound function is called. ```js function list() { return Array.prototype.slice.call(arguments); } var list1 = list(1, 2, 3); // [1, 2, 3] // Create a function with a preset leading argument var leadingThirtysevenList = list.bind(null, 37); var list2 = leadingThirtysevenList(); // [37] var list3 = leadingThirtysevenList(1, 2, 3); // [37, 1, 2, 3] ``` ### 配合 `setTimeout` By default within `window.setTimeout()` (en-US), the `this` keyword will be set to the `window` (en-US) (or `global`) object. When working with class methods that require `this` to refer to class instances, you may explicitly bind `this` to the callback function, in order to maintain the instance. ```js function LateBloomer() { this.petalCount = Math.floor(Math.random() \* 12) + 1; } // Declare bloom after a delay of 1 second LateBloomer.prototype.bloom = function () { window.setTimeout(this.declare.bind(this), 1000); }; LateBloomer.prototype.declare = function () { console.log("I am a beautiful flower with " + this.petalCount + " petals!"); }; var flower = new LateBloomer(); flower.bloom(); // after 1 second, triggers the 'declare' method ``` ### Bound functions used as constructors **警告:** This section demonstrates JavaScript capabilities and documents some edge cases of the `bind()` method. The methods shown below are not the best way to do things and probably should not be used in any production environment. Bound functions are automatically suitable for use with the `new` operator to construct new instances created by the target function. When a bound function is used to construct a value, the provided `this` is ignored. However, provided arguments are still prepended to the constructor call: ```js function Point(x, y) { this.x = x; this.y = y; } Point.prototype.toString = function () { return this.x + "," + this.y; }; var p = new Point(1, 2); p.toString(); // '1,2' // not supported in the polyfill below, // works fine with native bind: var YAxisPoint = Point.bind(null, 0 /\*x\*/); var emptyObj = {}; var YAxisPoint = Point.bind(emptyObj, 0 /\*x\*/); var axisPoint = new YAxisPoint(5); axisPoint.toString(); // '0,5' axisPoint instanceof Point; // true axisPoint instanceof YAxisPoint; // true new Point(17, 42) instanceof YAxisPoint; // true ``` Note that you need do nothing special to create a bound function for use with `new`. The corollary is that you need do nothing special to create a bound function to be called plainly, even if you would rather require the bound function to only be called using `new`. ```js // Example can be run directly in your JavaScript console // ...continuing from above // Can still be called as a normal function // (although usually this is undesired) YAxisPoint(13); emptyObj.x + "," + emptyObj.y; // > '0,13' ``` If you wish to support the use of a bound function only using `new`, or only by calling it, the target function must enforce that restriction. ### Creating shortcuts `bind()` is also helpful in cases where you want to create a shortcut to a function which requires a specific **`this`** value. Take `Array.prototype.slice`, for example, which you want to use for converting an array-like object to a real array. You could create a shortcut like this: ```js var slice = Array.prototype.slice; // ... slice.apply(arguments); ``` With `bind()`, this can be simplified. In the following piece of code, `slice` is a bound function to the `apply()` function of `Function.prototype` (en-US), with the **`this`** value set to the `slice()` function of `Array.prototype`. This means that additional `apply()` calls can be eliminated: ```js // same as "slice" in the previous example var unboundSlice = Array.prototype.slice; var slice = Function.prototype.apply.bind(unboundSlice); // ... slice(arguments); ``` Polyfill -------- You can partially work around this by inserting the following code at the beginning of your scripts, allowing use of much of the functionality of `bind()` in implementations that do not natively support it. ```js if (!Function.prototype.bind) { Function.prototype.bind = function (oThis) { if (typeof this !== "function") { // closest thing possible to the ECMAScript 5 // internal IsCallable function throw new TypeError( "Function.prototype.bind - what is trying to be bound is not callable", ); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function () {}, fBound = function () { return fToBind.apply( this instanceof fNOP ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments)), ); }; if (this.prototype) { // Function.prototype doesn't have a prototype property fNOP.prototype = this.prototype; } fBound.prototype = new fNOP(); return fBound; }; } ``` Some of the many differences (there may well be others, as this list does not seriously attempt to be exhaustive) between this algorithm and the specified algorithm are: * The partial implementation relies on `Array.prototype.slice()`, `Array.prototype.concat()`, `Function.prototype.call()` and `Function.prototype.apply()`, built-in methods to have their original values. * The partial implementation creates functions that do not have immutable "poison pill" `caller` (en-US) and `arguments` properties that throw a `TypeError` (en-US) upon get, set, or deletion. (This could be added if the implementation supports `Object.defineProperty`, or partially implemented [without throw-on-delete behavior] if the implementation supports the `Object.prototype.__defineGetter__()` (en-US) and `Object.prototype.__defineSetter__()` (en-US) extensions.) * The partial implementation creates functions that have a `prototype` property. (Proper bound functions have none.) * The partial implementation creates bound functions whose `length` property does not agree with that mandated by ECMA-262: it creates functions with length 0, while a full implementation, depending on the length of the target function and the number of pre-specified arguments, may return a non-zero length. If you choose to use this partial implementation, **you must not rely on those cases where behavior deviates from ECMA-262, 5th edition!** With some care, however (and perhaps with additional modification to suit specific needs), this partial implementation may be a reasonable bridge to the time when `bind()` is widely implemented according to the specification. Please check https://github.com/Raynos/function-bind for a more thorough solution! 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-function.prototype.bind | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 相關連結 ---- * `Function.prototype.apply()` * `Function.prototype.call()` * Functions (en-US)
Date.prototype.valueOf() - JavaScript
Date.prototype.valueOf() ======================== **`valueOf()`** 方法回傳 `Date` 物件的原始值。 嘗試一下 ---- 語法 -- ```js valueOf() ``` ### 返回值 從 1970 年 1 月 1 日 00:00:00 UTC 至給定日期之間的毫秒數,若為無效日期則回傳 `NaN` 。 描述 -- `valueOf()` 方法以數字型別回傳一 `Date` 物件的原始值,亦即自 1970 年 1 月 1 日 00:00:00 UTC 起所經過的毫秒數。 此方法在功能上相當於 `Date.prototype.getTime()` 。 通常此方法由 JavaScript 內部呼叫,而非明確寫在程式碼中。 範例 -- ### 使用 valueOf() ```js const x = new Date(56, 6, 17); const myVar = x.valueOf(); // 指派 -424713600000 至 myVar ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-date.prototype.valueof | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Object.prototype.valueOf()` (en-US) * `Date.prototype.getTime()`
Date.prototype.setUTCHours() - JavaScript
Date.prototype.setUTCHours() ============================ **`setUTCHours()`** 方法根據世界時設置指定日期的小時,並回傳自 1970 年 1 月 1 日 00:00:00 UTC 至更新的 `Date` 實例所表示的時間為止,經過的毫秒數。 嘗試一下 ---- 語法 -- ```js setUTCHours(hoursValue) setUTCHours(hoursValue, minutesValue) setUTCHours(hoursValue, minutesValue, secondsValue) setUTCHours(hoursValue, minutesValue, secondsValue, msValue) ``` ### 參數 `hoursValue` 一個表示小時、介於 0 至 23 之間的整數。 `minutesValue` 可選的。一個表示分鐘、介於 0 至 59 之間的整數。 `secondsValue` 可選的。一個表示秒數、介於 0 至 59 之間的整數。若給定 `secondsValue`,則必須同時給定 `minutesValue` 參數值。 `msValue` 可選的。一個表示毫秒數、介於 0 至 999 之間的數。若給定 `msValue` 的值,則必須同時給定 `minutesValue` 與 `secondsValue` 參數值。 ### 返回值 1970 年 1 月 1 日 00:00:00 UTC 與更新日期之間的毫秒差異數。 描述 -- 如果沒有指明 `minutesValue`、`secondsValue` 與 `msValue` 參數值,則會使用 `getUTCMinutes()`、`getUTCSeconds()`、`getUTCMilliseconds()` 方法回傳的值。 如果給定的參數值超出預期範圍,`setUTCHours()` 會相對應地更新 `Date` 物件的日期資訊。例如,`secondsValue` 傳入 100 ,分鐘數將增加 1(`minutesValue + 1`)、其餘的 40 則計入秒數。 範例 -- ### 使用 setUTCHours() ```js const theBigDay = new Date(); theBigDay.setUTCHours(8); ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-date.prototype.setutchours | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Date.prototype.getUTCHours()` * `Date.prototype.setHours()`
Date.prototype.getUTCMinutes() - JavaScript
Date.prototype.getUTCMinutes() ============================== **`getUTCMinutes()`** 方法根據世界時回傳指定日期的分鐘數。 嘗試一下 ---- 語法 -- ```js getUTCMinutes() ``` ### 返回值 若 `Date` 物件為有效日期,則根據 UTC 時間回傳一個表示分鐘數、介於 0 至 59 之間的整數;若為無效日期,則回傳 `Number.NaN()` (en-US)。 範例 -- ### 使用 getUTCMinutes() 下列範例指派當前時間的分鐘至變數 `minutes`。 ```js const today = new Date(); const minutes = today.getUTCMinutes(); ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-date.prototype.getutcminutes | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Date.prototype.getMinutes()` * `Date.prototype.setUTCMinutes()` (en-US)
Date.prototype.getMilliseconds() - JavaScript
Date.prototype.getMilliseconds() ================================ **`getMilliseconds()`** 方法基於本地時區回傳指定日期的毫秒數。 嘗試一下 ---- 語法 -- ```js getMilliseconds() ``` ### 返回值 一個基於本地時區表示指定日期的毫秒數、介於 0 至 999 的整數值。 範例 -- ### 使用 getMilliseconds() 下列範例將當前時間的毫秒數指派給變數 `milliseconds`。 ```js const today = new Date(); const milliseconds = today.getMilliseconds(); ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-date.prototype.getmilliseconds | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Date.prototype.getUTCMilliseconds()` * `Date.prototype.setMilliseconds()` (en-US)
Date.prototype.getSeconds() - JavaScript
Date.prototype.getSeconds() =========================== **`getSeconds()`** 方法基於本地時區回傳指定日期的秒數。 嘗試一下 ---- 語法 -- ```js getSeconds() ``` ### 返回值 一個基於本地時區表示指定日期的秒數、介於 0 至 59 的整數值。 範例 -- ### 使用 getSeconds() 下方第二行陳述式將 `Date` 物件 `xmas95` 的值 30,指派給變數 `seconds`。 ```js const xmas95 = new Date("December 25, 1995 23:15:30"); const seconds = xmas95.getSeconds(); console.log(seconds); // 30 ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-date.prototype.getseconds | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Date.prototype.getUTCSeconds()` * `Date.prototype.setSeconds()` (en-US)
Date.prototype.setHours() - JavaScript
Date.prototype.setHours() ========================= **`setHours()`** 方法基於本地時區設置指定日期的小時,並回傳自 1970 年 1 月 1 日 00:00:00 UTC 起至更新的 `Date` 實例所表示的時間為止,共經過的毫秒數。 嘗試一下 ---- 語法 -- ```js setHours(hoursValue) setHours(hoursValue, minutesValue) setHours(hoursValue, minutesValue, secondsValue) setHours(hoursValue, minutesValue, secondsValue, msValue) ``` ### 參數 `hoursValue` 表示小時,理想上為介於 0 至 23 之間的整數。若傳入的值大於 23,溢出時數會增加日期時間。 `minutesValue` 可選的。表示分鐘,理想上為介於 0 至 59 之間的整數。若傳入的值大於 59,溢出分鐘數會增加日期時間。 `secondsValue` 可選的。表示秒,理想上為介於 0 至 59 之間的整數。若傳入的值大於 59,溢出秒數會增加日期時間。若給定 `secondsValue`,則必須同時給定 `minutesValue` 參數值。 `msValue` 可選的。表示毫秒,理想上為介於 0 至 999 之間的數。若傳入的值大於 999,溢出毫秒數會增加日期時間。若給定 `msValue` 的值,則必須同時給定 `minutesValue` 與 `secondsValue` 參數值。 ### 返回值 1970 年 1 月 1 日 00:00:00 UTC 與更新日期之間的毫秒差異數。 描述 -- 如果沒有指明 `minutesValue`、`secondsValue` 與 `msValue` 參數值,則會使用 `getMinutes()`、`getSeconds()`、`getMilliseconds()` 方法回傳的值。 如果給定的參數值超出預期範圍,`setHours()` 會相對應地更新 `Date` 物件的日期資訊。例如,`secondsValue` 傳入 100 ,分鐘數將增加 1(`minutesValue + 1`)、其餘的 40 則計入秒數。 範例 -- ### 使用 setHours() ```js const theBigDay = new Date(); theBigDay.setHours(7); ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-date.prototype.sethours | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Date.prototype.getHours()` * `Date.prototype.setUTCHours()`
Date.prototype.getDay() - JavaScript
Date.prototype.getDay() ======================= **`getDay()`** 方法會根據當地時間將指定日期返回一星期中的第幾天,其中 0 代表星期日。 在當月的某天可以參考`Date.prototype.getDate()` (en-US)。 嘗試一下 ---- 語法 -- ``` dateObj.getDay() ``` ### 返回值 返回一個整數,數值介於 0 到 6 之間,取決於當地時間對應出指定日期為星期幾:0 代表星期日,1 代表星期一,2 代表星期二,依此類推。 範例 -- ### 使用 `getDay()` 下面第二行表示根據日期對象'Xmas95'的值,把 1 賦值給'weekday'。則 1995 年 12 月 25 日是星期一。 ```js var Xmas95 = new Date("December 25, 1995 23:15:30"); var weekday = Xmas95.getDay(); console.log(weekday); // 1 ``` **備註:** 如果需要,可以使用`Intl.DateTimeFormat` (en-US)加上`options`參數來獲取星期幾全名。使使用此方法能輕鬆做出各種國際語言: ```js var options = { weekday: "long" }; console.log(new Intl.DateTimeFormat("en-US", options).format(Xmas95)); // Monday console.log(new Intl.DateTimeFormat("de-DE", options).format(Xmas95)); // Montag ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-date.prototype.getday | 瀏覽器兼容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Date.prototype.getUTCDate()` (en-US) * `Date.prototype.getUTCDay()` (en-US) * `Date.prototype.setDate()` (en-US)
Date.prototype.getUTCHours() - JavaScript
Date.prototype.getUTCHours() ============================ **`getUTCHours()`** 方法根據世界時回傳指定日期的小時數。 嘗試一下 ---- 語法 -- ```js getUTCHours() ``` ### 返回值 若 `Date` 物件為有效日期,則根據 UTC 時間回傳一個表示小時、介於 0 至 23 之間的整數;若為無效日期,則回傳 `Number.NaN()` (en-US)。 範例 -- ### 使用 getUTCHours() 下列範例指派當前時間的小時至變數 `hours`。 ```js const today = new Date(); const hours = today.getUTCHours(); ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-date.prototype.getutchours | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Date.prototype.getHours()` * `Date.prototype.setUTCHours()`
Date.prototype.getTime() - JavaScript
Date.prototype.getTime() ======================== **`getTime()`** 方法回傳自 1970 年 1 月 1 日 00:00:00 UTC 起經過的毫秒數。 你可以透過此方法指派一日期與時間至另一 `Date` 物件。這個方法在功能上與 `valueOf()` 相同。 嘗試一下 ---- 語法 -- ```js getTime() ``` ### 返回值 一個表示自 1970 年 1 月 1 日 00:00:00 UTC 至給定日期為止,所經過的毫秒數。 描述 -- `new Date().getTime()` 的精確度可能會依瀏覽器設定而做取捨,以防止時序攻擊(timing attack)與指紋辨識(fingerprinting)。如 Firefox 預設會開啟 `privacy.reduceTimerPrecision`,在 Firefox 59 預設為 20µs、Firefox 60 為 2ms。 ```js // 在 Firefox 60 中降低的時間精確度(2ms) new Date().getTime(); // 1519211809934 // 1519211810362 // 1519211811670 // … // 啟用 `privacy.resistFingerprinting` 而降低的時間精確度 new Date().getTime(); // 1519129853500 // 1519129858900 // 1519129864400 // … ``` Firefox 內也可以啟用 `privacy.resistFingerprinting`,將擇 100ms 或 `privacy.resistFingerprinting.reduceTimerPrecision.microseconds` 的值當中較大者調整精確度。 範例 -- ### 使用 `getTime()` 複製日期 建構一個相同時間值的日期物件。 ```js // 因為月份是從零開始,故 birthday 將為 1995 年 1 月 10 日 const birthday = new Date(1994, 12, 10); const copy = new Date(); copy.setTime(birthday.getTime()); ``` ### 測量執行時間 在兩個新建立的 `Date` 物件接連呼叫 `getTime()` 方法,並相減兩者返回時間。可透過此法計算某些操作的執行時間。參見 `Date.now()` 以避免產生非必要的 `Date` 物件。 ```js let end, start; start = new Date(); for (let i = 0; i < 1000; i++) { Math.sqrt(i); } end = new Date(); console.log(`Operation took ${end.getTime() - start.getTime()} msec`); ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-date.prototype.gettime | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Date.prototype.setTime()` * `Date.prototype.valueOf()` * `Date.now()`
Date.parse() - JavaScript
Date.parse() ============ **`Date.parse()`** 方法解析一表示日期的字串,並回傳自 1970 年 01 月 01 日 00:00:00 UTC 起至該日期共經過的毫秒數;如果字串無法辨識或包含無效值(如:2015-02-31),則回傳 `NaN`。 只有 ISO 8601 格式( `YYYY-MM-DDTHH:mm:ss.sssZ`)為明確指定支援的格式。其餘格式因實作方式而異,不一定跨瀏覽器通用。若需要涵蓋多種格式,可以引入函式庫協助。 嘗試一下 ---- 語法 -- ```js Date.parse(dateString) ``` 參數 -- `dateString` 一個簡化表示 ISO 8601 日曆日期延伸格式的字串。(亦可使用其他格式,但結果會依實作方式而定。) ### 返回值 一個自 1970 年 01 月 01 日 00:00:00 UTC 起,至解析字串而得的日期為止,所經過的毫秒數值。如果該參數並非有效日期,則回傳 `NaN` 。 描述 -- `parse()` 方法接受一日期字串(例如: `"2011-10-10T14:48:00"`)並回傳自 1970 年 01 月 01 日 00:00:00 UTC 至該日期所經過的毫秒數。 此函式實用於設定日期,例如結合使用 `setTime()` 方法與 `Date` 物件。 ### 日期字串格式 呈現日期時間的標準字串格式乃 ISO 8601 日曆日期延伸格式的簡化版。(詳細請參見 ECMAScript 規範的 Date Time String Format章節) 例如,`"2011-10-10"`(*只有日期*)、`"2011-10-10T14:48:00"`(*日期與時間*),或 `"2011-10-10T14:48:00.000+09:00"`(*日期與時間至毫秒級以及時區*)皆可作為有效參數傳入並解析。如果沒有指明時差,只有日期的參數會假設為 UTC 時間,而有日期與時間的參數會當作是本地時間。 解析日期字串的過程雖然會加註時區,但回傳值必定是從 1970 年 01 月 01 日 00:00:00 UTC 起至該參數表示的日期為止,所經過的毫秒數;或是 `NaN`。 因為 `parse()` 是 `Date` 的靜態方法,故會以 `Date.parse()` 而非作為 `Date` 實例的方法呼叫。 ### 退回至實作定義的日期格式 **備註:** 此段落包含因實作而異的行為,不同實作間可能不一致。 ECMAScript 規範表明:如果字串不符合標準格式,函式可能會退回至實作定義的啟發式或解析演算法。無法辨識的字串或包含無效值的 ISO 格式字串將使 `Date.parse()` 回傳 `NaN`。 不過無效且非 ECMA-262 定義的 ISO 格式的日期字串,其回傳結果會依瀏覽器與實際值而異,不一定回傳 `NaN`,例如: ```js // 非 ISO 字串且含無效日期值 new Date("23/25/2014"); ``` 在 Firefox 30 當中會被視為本地時間的 2015 年 11 月 25 日,而 Safari 7 中則為無效日期。 但如果為 ISO 格式的字串而包含無效值,則會回傳 `NaN`: ```js // ISO 字串且含無效日期值 new Date("2014-25-23").toISOString(); // throws "RangeError: invalid date" ``` SpiderMonkey 的實作啟發可見 `jsdate.cpp`。例如 `"10 06 2014"` 即不符合 ISO 格式,故會執行自定義解析。參見 rough outline 以瞭解運作原理。 ```js new Date("10 06 2014"); ``` 會被視為本地時間的 2014 年 10 月 06 日 而非 2014 年 06 月 10 日。 其他範例: ```js new Date("foo-bar 2014").toString(); // returns: "Invalid Date" Date.parse("foo-bar 2014"); // returns: NaN ``` ### 假定時區上的差異 **備註:** 此段落包含因實作而異的行為,不同實作間可能不一致。 給定一非標準的字串 `"March 7, 2014"`,`parse()` 會假定為本地時區;但如果是簡化版的 ISO 8601 日曆日期延伸格式的字串,如 `"2014-03-07"`,則會假定為 UTC 時區。故,除非系統為 UTC 時區,否則依支援的 ECMAScript 版本,由該字串產生的 `Date` 物件可能呈現不同時間。亦即兩個看似相等的日期字串,依傳入的格式而可能產生不同解析結果。 範例 -- ### 使用 Date.parse() 下列呼叫皆會回傳 `1546300800000`。第一個隱含為 UTC 時間,其餘則以 ISO 日期規範(`Z` 與 `+00:00`)明確表示 UTC 時區。 ```js Date.parse("2019-01-01"); Date.parse("2019-01-01T00:00:00.000Z"); Date.parse("2019-01-01T00:00:00.000+00:00"); ``` 以下呼叫並未指明時區,將會設定為使用者系統時區的 2019-01-01 00:00:00。 ```js Date.parse("2019-01-01T00:00:00"); ``` ### 非標準的日期字串 **備註:** 此段落包含因實作而異的行為,不同實作間可能不一致。 若 `ipoDate` 為既有的 `Date` 物件,可將其設定為本地時間的 1995-08-09,如下: ```js ipoDate.setTime(Date.parse("Aug 9, 1995")); ``` 其他解析非標準日期字串的範例: ```js Date.parse("Aug 9, 1995"); ``` 因為此字串未指明時區、且並非 ISO 格式,故預設為本地時區。如在 GMT-0300 時區回傳 `807937200000`,其他時區另計。 ```js Date.parse("Wed, 09 Aug 1995 00:00:00 GMT"); ``` 因為已指明 GMT (UTC) 時區,不論本地時區為何,皆回傳 `807926400000`。 ```js Date.parse("Wed, 09 Aug 1995 00:00:00"); ``` 因為參數內沒有指明時區,而且並非 ISO 格式,因此視為本地時間。在 GMT-0300 時區會回傳 `807937200000`,其他時區另計。 ```js Date.parse("Thu, 01 Jan 1970 00:00:00 GMT"); ``` 因為已指明 GMT (UTC) 時區,不論本地時區為何,皆回傳 `0`。 ```js Date.parse("Thu, 01 Jan 1970 00:00:00"); ``` 因為此字串未指明時區、且並非 ISO 格式,故預設為本地時區。如在 GMT-0400 回傳 `14400000`,其他時區另計。 ```js Date.parse("Thu, 01 Jan 1970 00:00:00 GMT-0400"); ``` 因為已指明 GMT (UTC) 時區,不論本地時區為何,皆回傳 `14400000`。 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-date.parse | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. ### 相容性資訊 * Firefox 49 將解析兩位數年份的方式從與 Internet Explorer 改為與 Google Chrome 一致。現在小於 `50` 的兩位數年份會解析為 21 世紀年份。例如 `04/16/17`,先前會視為 1917 年 04 月 16 日;現在則解析為 2017 年 04 月 16 日。建議使用 ISO 8601 格式如 `"2017-04-16"`,以避免任何互通性問題或不明確的年份。(bug 1265136) * Google Chrome 視數字字串為有效的 `dateString` 參數。例如 `!!Date.parse("42")` 在 Firefox 會評估為 `false`,而在 Google Chrome 會評估為 `true`;因為 `"42"` 被當作是 2042 年 01 月 01 日。 參見 -- * `Date.UTC()`
Date.prototype.setTime() - JavaScript
Date.prototype.setTime() ======================== **`setTime()`** 方法將從 1970 年 01 月 01 日 00:00:00 UTC 起所經過的毫秒數設置為 `Date` 物件的值。 嘗試一下 ---- 語法 -- ```js setTime(timeValue) ``` ### 參數 `timeValue` 一個整數,表示自 1970 年 01 月 01 日 00:00:00 UTC 起所經過的毫秒數。 ### 返回值 1970 年 01 月 01 日 00:00:00 UTC 與更新日期之間的毫秒數(實際上是參數值)。 描述 -- 以 `setTime()` 方法指派一日期與時間至另一 `Date` 物件。 範例 -- ### 使用 setTime() ```js const theBigDay = new Date("July 1, 1999"); const sameAsBigDay = new Date(); sameAsBigDay.setTime(theBigDay.getTime()); ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-date.prototype.settime | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Date.prototype.getTime()` * `Date.prototype.setUTCHours()`
Date.now() - JavaScript
Date.now() ========== **`Date.now()`** 方法回傳自 1970/01/01 00:00:00 UTC 起經過的毫秒數。 格式 -- ``` var timeInMs = Date.now(); ``` ### 回傳值 一個代表由經 UNIX 紀元起經過的毫秒數值(`Number`)。 描述 -- 由於 `now()` 是 `Date` 的靜態方法,你只能用 `Date.now()` 的方式呼叫它。 補完 -- 這個函數是 ECMA-262 第 5 版的標準。 對於未更新支援此方法的引擎,可以利用底下的程式補上: ```js if (!Date.now) { Date.now = function now() { return new Date().getTime(); }; } ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-date.now | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 相關資源 ---- * `Performance.now()` (en-US) — 提供亞毫秒級的時間戳記,作為評估網頁效能的解決方案。 * `console.time()` (en-US) / `console.timeEnd()` (en-US)
Date.prototype.getMinutes() - JavaScript
Date.prototype.getMinutes() =========================== **`getMinutes()`** 方法基於本地時區回傳指定日期的分鐘數。 嘗試一下 ---- 語法 -- ```js getMinutes() ``` ### 返回值 一個基於本地時區表示指定日期的分鐘數、介於 0 至 59 的整數值。 範例 -- ### 使用 getMinutes() 下方第二行陳述式將 `Date` 物件 `xmas95` 的值 15,指派給變數 `minutes`。 ```js const xmas95 = new Date("December 25, 1995 23:15:30"); const minutes = xmas95.getMinutes(); console.log(minutes); // 15 ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-date.prototype.getminutes | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Date.prototype.getUTCMinutes()` * `Date.prototype.setMinutes()` (en-US)
Date.prototype.getUTCMilliseconds() - JavaScript
Date.prototype.getUTCMilliseconds() =================================== **`getUTCMilliseconds()`** 方法根據世界時回傳指定日期的毫秒數。 嘗試一下 ---- 語法 -- ```js getUTCMilliseconds() ``` ### 返回值 若 `Date` 物件為有效日期,則根據 UTC 時間回傳一個表示毫秒數、介於 0 至 999 之間的整數;若為無效日期,則回傳 `Number.NaN()` (en-US)。 別與 Unix 時間搞混了。應使用 `Date.prototype.getTime()` 方法取得自 1970/01/01 起經過的毫秒數。 範例 -- ### 使用 getUTCMilliseconds() 下列範例指派當前時間的毫秒數至變數 `milliseconds` 。 ```js const today = new Date(); const milliseconds = today.getUTCMilliseconds(); ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-date.prototype.getutcmilliseconds | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Date.prototype.getMilliseconds()` * `Date.prototype.setUTCMilliseconds()` (en-US)
Date.UTC() - JavaScript
Date.UTC() ========== **`Date.UTC()`** 方法接受與建構子相同長度的參數,將參數視為通用時間(UTC)來計算回傳由 1970-01-01 00:00:00 UTC 所經過的毫秒數。 格式 -- ``` Date.UTC(year, month[, day[, hour[, minute[, second[, millisecond]]]]]) ``` ### 參數 `year` 1900 年後的年份。 `month` 月份,介於 0 到 11 之間。 `day` 選用。月份中的日期,介於 1 到 31 之間。 `hour` 選用。小時,介於 0 到 23 之間。 `minute` 選用。分鐘數,介於 0 到 59 之間。 `second` 選用。秒數,介於 0 到 59 之間。 `millisecond` 選用。毫秒數 0 到 999 之間。 ### 回傳值 得到傳入這個 `Date` 方法的參數所代表時間,與 1970-01-01 00:00:00 UTC 相差的毫秒數。 描述 -- `UTC()` 取得以逗號分隔的時間參數,回傳 1970-01-01 00:00:00 UTC 與該時間相差的毫秒數。 你應該指定完成的年份資料,例如: 1998。如果一個 0 到 99 的年份被指定,這個方法會將它轉換為 20 世紀的年份(變為 19xx 年),例如你傳入 95 ,則會被當作 1995 年被指定。 這個 `UTC()` 方法與 `Date` 建構子有兩個地方不同。 * `Date.UTC()` 使用 UTC 時區而不是當地時區。 * `Date.UTC()` 回傳一個數值而不是 `Date` 物件。 當你指定參數超出預期的範圍, UTC( ) 方法會去調整其它的參數使之成立。比如如果你指定月份為 15 ,年份將被加 1 ,以 3 作為傳入的月份。 因為 UTC( ) 是 `Date` 的一個靜態方法,只能使用 `Date.UTC()` 的方式呼叫,而不能由建立出來的 `Date` 物件去執行它。 範例 -- ### 使用 `Date.UTC()` 以下利用它來將指定的時間以 UTC 而非本地時間的方式來建立 `Date` 物件: ```js var utcDate = new Date(Date.UTC(96, 11, 1, 0, 0, 0)); ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-date.utc | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 相關資源 ---- * `Date.parse()`
Date.prototype.getUTCSeconds() - JavaScript
Date.prototype.getUTCSeconds() ============================== **`getUTCSeconds()`** 方法根據世界時回傳指定日期的秒數。 嘗試一下 ---- 語法 -- ```js getUTCSeconds() ``` ### 返回值 若 `Date` 物件為有效日期,則根據 UTC 時間回傳一個表示秒數、介於 0 至 59 之間的整數;若為無效日期,則回傳 `Number.NaN()` (en-US)。 範例 -- ### 使用 getUTCSeconds() 下列範例指派當前時間的秒數至變數 `seconds`。 ```js const today = new Date(); const seconds = today.getUTCSeconds(); ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-date.prototype.getutcseconds | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Date.prototype.getSeconds()` * `Date.prototype.setUTCSeconds()` (en-US)
Date.prototype.getHours() - JavaScript
Date.prototype.getHours() ========================= **`getHours()`** 方法基於本地時區回傳指定日期的小時數。 嘗試一下 ---- 語法 -- ```js getHours() ``` ### 返回值 一個基於本地時區表示指定日期的小時、介於 0 至 23 的整數值。 範例 -- ### 使用 getHours() 下方第二行陳述式將 `Date` 物件 `xmas95` 的值 23,指派給變數 `hours`。 ```js const xmas95 = new Date("December 25, 1995 23:15:30"); const hours = xmas95.getHours(); console.log(hours); // 23 ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-date.prototype.gethours | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Date.prototype.getUTCHours()` * `Date.prototype.setHours()`
Number.prototype.toFixed() - JavaScript
Number.prototype.toFixed() ========================== **`toFixed()`** 方法會使用定點小數表示法(fixed-point notation)來格式化數字。 嘗試一下 ---- 語法 -- ```js numObj.toFixed([digits]) ``` ### 參數 `digits 小數位` 選擇性輸入。顯示數值至多少個小數點,範圍由 0 到 20 之間,執行時或可支援非常大範圍的數值。如果無輸入會默認做 0。 ### 回傳值 一個代表以定點小數表示法(fixed-point notation)格式化數字後的字串。 ### 例外 `RangeError` If `digits` is too small or too large. Values between 0 and 100, inclusive, will not cause a `RangeError`. Implementations are allowed to support larger and smaller values as chosen. `TypeError` (en-US) If this method is invoked on an object that is not a `Number`. 說明 -- **`toFixed()`** returns a string representation of `numObj` that does not use exponential notation and has exactly `digits` digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If `numObj` is greater than `1e+21`, this method simply calls `Number.prototype.toString()` (en-US) and returns a string in exponential notation. 範例 -- ### Using `toFixed` ```js var numObj = 12345.6789; numObj.toFixed(); // Returns '12346': note rounding, no fractional part numObj.toFixed(1); // Returns '12345.7': note rounding numObj.toFixed(6); // Returns '12345.678900': note added zeros (1.23e20).toFixed(2); // Returns '123000000000000000000.00' (1.23e-10).toFixed(2); // Returns '0.00' (2.34).toFixed(1); // Returns '2.3' (2.35).toFixed(1); // Returns '2.4'. Note that it rounds up in this case. -(2.34).toFixed(1); // Returns -2.3 (due to operator precedence, negative number literals don't return a string...) (-2.34).toFixed(1); // Returns '-2.3' (...unless you use parentheses) ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-number.prototype.tofixed | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Number.prototype.toExponential()` * `Number.prototype.toPrecision()` (en-US) * `Number.prototype.toString()` (en-US)
Number.prototype.toExponential() - JavaScript
Number.prototype.toExponential() ================================ **`toExponential()`** method 用來將數字轉成「科學記數法」格式。 語法 -- ```js numObj.toExponential([fractionDigits]) ``` ### 參數 | 參數 | 可選 | 默認值 | 類型 | 說明 | | --- | --- | --- | --- | --- | | `fractionDigits` | ● | 默認盡可能將數字完整顯示 | `Number`(正整數) | 小數點後的位數。需為 0 至 20 之間。 | ### 回傳值 一 string,將數字以「科學計數法」格式表示出來 ### Exceptions `RangeError` 若 `fractionDigits` 超出範圍(可接受的範圍是 0 ~ 20 之間的正整數)觸發 `RangeError`。 `TypeError` (en-US) 若參數 `fractionDigits` 不是 `Number`,則觸發`TypeError` (en-US)。 Description ----------- If the `fractionDigits` argument is omitted, the number of digits after the decimal point defaults to the number of digits necessary to represent the value uniquely. If you use the `toExponential()` method for a numeric literal and the numeric literal has no exponent and no decimal point, leave whitespace(s) before the dot that precedes the method call to prevent the dot from being interpreted as a decimal point. If a number has more digits than requested by the `fractionDigits` parameter, the number is rounded to the nearest number represented by `fractionDigits` digits. See the discussion of rounding in the description of the `toFixed()` method, which also applies to `toExponential()`. 範例 -- ### Using `toExponential` ```js var numObj = 77.1234; console.log(numObj.toExponential()); // logs 7.71234e+1 console.log(numObj.toExponential(4)); // logs 7.7123e+1 console.log(numObj.toExponential(2)); // logs 7.71e+1 console.log((77.1234).toExponential()); // logs 7.71234e+1 console.log((77).toExponential()); // logs 7.7e+1 ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-number.prototype.toexponential | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `Number.prototype.toFixed()` * `Number.prototype.toPrecision()` (en-US) * `Number.prototype.toString()` (en-US)
可選串連 - JavaScript
可選串連 ==== **可選串連**運算子 **`?.`** 允許進行深層次的物件值存取,而無需透過明確的物件值串連驗證。`?.` 運算子的操作與 `.` 屬性存取運算子相似,後者會在參照到 nullish (en-US) (`null` (en-US) or `undefined` (en-US)) 的值時出現錯誤,而前者可選串連則回傳 `undefined` 。 當需要存取一個函數,而這函數並不存在時,則會回傳 `undefined` 。 當有機會存在參照不存在的時候,可選串連可以提供更簡短的表述式來進行串連性的屬性存取。這有助於在無法保證物件屬性為必要存在的狀況下,進行物件內容的探索。 嘗試一下 ---- 語法 -- ``` obj?.prop obj?.[expr] arr?.[index] func?.(args) ``` 描述 -- 當串連物件裡面的參照或方法可能是`undefined` 或 `null` 時,可選串連運算子提供簡單的方法去存取這些串連物件下的值。 舉例來說,當一個物件 `obj` 是巢狀結構時,在沒有可選串連之下,要去查找一深層的屬性值需要驗證每層間的參照連結: ```js let nestedProp = obj.first && obj.first.second; ``` `obj.first` 的值需要先確定不是 `null` 值(和並非 `undefined` ),才能存取 `obj.first.second` 的值。這才能避免在存取值時,因為直接使用 `obj.first.second` 而沒有測試 `obj.first` 之下帶來的錯誤。 當使用了可選串連運算子(`?.`),你不再需要明確地進行測測,並能在基於 `obj.first` 的狀態下直接回傳,忽略存取 `obj.first.second` 的動作: ```js let nestedProp = obj.first?.second; ``` 從只是 `.` 改用作 `?.` 運算子,JavaScript 會知道在存取 `obj.first.second` 之前,需要間接地檢查並確保 `obj.first` 並不是 `null` 或 `undefined` 。當 `obj.first` 是 `null` 或 `undefined` ,運算式會像短路一樣跳過整個串連存取式,而回傳 `undefined` 。 這是跟以下是相等同的,但是實際上是不會建立臨時變數: ```js let temp = obj.first; let nestedProp = temp === null || temp === undefined ? undefined : temp.second; ``` ### 可選串連呼叫函數 你可以使用可選串連來嘗試呼叫一個或許沒有存在的方法。這可能有助於,舉例來說,使用一些未能提供服務的 API ,這可能因為過時的應用或是使用者的裝置未能支援某種功能。 當需要使用的方法並不存在時,透過可選串連去進行呼叫將不會抛出錯誤,取而代之的是回傳 `undefined` : ```js let result = someInterface.customMethod?.(); ``` **備註:** 假如物件有同樣的屬性名稱,而不是一個方法,使用 `?.` 將會抛出 `TypeError` (en-US) 錯誤(`x.y 不是一個函數`)。 #### 處理回呼函式或事件處理器 如果你使用回呼函式,或是透過解構賦值來擷取物件中的方法,你可能會因為這些方法沒有存在,而無法進行呼叫,除非你事先驗證其存在性。所以,你可以利用 `?.` 來避免這樣的測試: ```js // 在 ES2019 下撰寫 function doSomething(onContent, onError) { try { // ... 對資料進行一些處理 } catch (err) { if (onError) { // 測試 onError 是否真的存在 onError(err.message); } } } ``` ```js // 使用可選串連進行函式呼叫 function doSomething(onContent, onError) { try { // ... 對資料進行一些處理 } catch (err) { onError?.(err.message); // 就算 onError 是 undefined 也不會抛出錯誤 } } ``` ### 可選串連表述式 你也可以在方括號屬性存取 (en-US)表達式中使用可選串連: ```js let nestedProp = obj?.["prop" + "Name"]; ``` ### 矩陣項目的可選串連 ```js let arrayItem = arr?.[42]; ``` 範例 -- ### 基本範例 這個範例會找出 Map 物件中一個鍵為 `bar` 成員的 `name` 屬性值,但事實上並沒有相關成員。所以結果為 `undefined` 。 ```js let myMap = new Map(); myMap.set("foo", { name: "baz", desc: "inga" }); let nameBar = myMap.get("bar")?.name; ``` ### 短路式運算 當可選串連接上表述式時,如果左邊的運算數值是 `null` 或 `undefined` ,表述式則不會被運算。舉例來說: ```js let potentiallyNullObj = null; let x = 0; let prop = potentiallyNullObj?.[x++]; console.log(x); // 因為 x 沒有遞增,所以為 0 ``` ### 串接多個可選串連 在巢狀結構中可以使用多次的可選串連: ```js let customer = { name: "Carl", details: { age: 82, location: "Paradise Falls", // 詳細地址 address 並不知道 }, }; let customerCity = customer.details?.address?.city; // … 同樣地,串接多個可選串連來呼叫函式也是湊效的 let duration = vacations.trip?.getTime?.(); ``` ### 使用空值合併運算子 在可選串連後可以使用空值合併運算子 (en-US)來編配預設值,如果無法在屬性串連中取得值: ```js let customer = { name: "Carl", details: { age: 82 }, }; const customerCity = customer?.city ?? "Unknown city"; console.log(customerCity); // Unknown city ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # prod-OptionalExpression | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * 空值合併運算子 (en-US) * TC39 proposals
建構子函數的使用 - JavaScript
建構子函數的使用 ======== 還有一個選擇,你可以按照這兩個步驟來建立物件︰ 1. 編寫建構子函數以完成物件類型的定義。 2. 使用 new 建立物件的實體。 若要定義物件類型,就指定物件類型的名稱、屬性、方法並建立函數。舉例來說,假設你想要給 car 建立物件類型。你希望這個物件的類型稱作 `car`,而且你還希望他有 make、model、year 這些屬性。要做到這些,你需要編寫出以下的函數︰ ```js function car(make, model, year) { this.make = make; this.model = model; this.year = year; } ``` 注意 `this` 是用來把傳送給函數的值代入給物件的屬性。 現在你可以建立稱作 `mycar` 的物件如下所示︰ ```js mycar = new car("Eagle", "Talon TSi", 1993); ``` 這個語句建立 `mycar` 並且把指定的值代入給他自己的屬性。然後 `mycar.make` 的值是字串 "Eagle",`mycar.year` 是整數 1993,依此類推。 你可以藉由呼叫 `new` 來建立許多個 `car` 的物件。例如, ```js kenscar = new car("Nissan", "300ZX", 1992); vpgscar = new car("Mazda", "Miata", 1990); ``` 物件可以有另一個物件本身的屬性。例如,假設你定義稱為 `person` 的物件如下︰ ```js function person(name, age, sex) { this.name = name; this.age = age; this.sex = sex; } ``` 然後實體化兩個新的 person 物件如下︰ ```js rand = new person("Rand McKinnon", 33, "M"); ken = new person("Ken Jones", 39, "M"); ``` 然後你可以改寫 car 的定義,加入用來接受 `person` 物件的 owner 屬性,如下︰ ```js function car(make, model, year, owner) { this.make = make; this.model = model; this.year = year; this.owner = owner; } ``` 若要實體化新的物件,你可以如下使用︰ ```js car1 = new car("Eagle", "Talon TSi", 1993, rand); car2 = new car("Nissan", "300ZX", 1992, ken); ``` 注意,當建立新的物件的時候,傳入的並不是字面表達字串或整數值,上面的語句把 `rand` 和 `ken` 物件當作參數傳給 owners。然後如果你希望找出 car2 的 owner 的名稱,你可以如下存取屬性︰ ```js car2.owner.name ``` 注意,你永遠可以給之前定義的物件加入屬性。例如,語句 ```js car1.color = "black"; ``` 把 `color` 屬性加入給 car1,並且把 "black" 的值代入給新加入的屬性。然而,這樣並不能影響到其他的任何物件。若要給所有同樣類型的物件加入新的屬性,你必須把新的屬性加入到 car 物件類型的定義。
一元正號運算子(+) - JavaScript
一元正號運算子(+) ========== 一元正號運算子(`+`)置於運算元之前並取其數值。如果可以,亦會將之轉為數字。 嘗試一下 ---- 語法 -- ```js +x ``` 詳細說明 ---- 一元負號運算子(`-`)也可以轉換非數字,但正號運算子卻是將運算元轉換為數字的最快和首選方法。 它不會對該運算元進行任何其他操作。 它可以將字串轉為整數和浮點數(如果字串值符合);亦可使用在非字串的運算元,例如 `true`、`false`、`null`。 正號運算子支持十進制和十六進制整數(`0x` 前綴)、負數(雖然不適用於十六進制)格式。 若用於 BigInt 類型的值,會觸發 TypeError。 如果無法解析值,它會回傳 `NaN`。 範例 -- ### 使用於數字 ```js const x = 1; const y = -1; console.log(+x); // 1 console.log(+y); // -1 ``` ### 使用於非數字上 ```js +true // 1 +false // 0 +null // 0 +[] // 0 +function (val) { return val; } // NaN +1n // throws TypeError: Cannot convert BigInt value to number ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-unary-plus-operator | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * 相加運算子 * 相減運算子 * 相除運算子 * 相乘運算子 * 餘數運算子 (en-US) * 相乘運算子 * 指數運算子 * 遞減運算子 * 負號運算子
super - JavaScript
super ===== super 關鍵字被使用於通過函式存取父層 `super.prop` 與 `super[expr]` 表達有效在 method definition 與 classes 與 object literals (en-US). 語法 -- ``` super([arguments]); // calls the parent constructor. super.functionOnParent([arguments]); ``` 描述 -- 當使用建構子,`super` 關鍵字必須出現在`this` 關鍵字之前使用,`super` 關鍵字也可以使用在呼叫函式與父對象 範例 -- ### 在類別中使用 `super` 這個程式碼片段從 classes sample (live demo). 這裏的 `super()` 被呼叫去避免複製到建構子的 `Rectangle` 與 `Square` 的共通部分。 ```js class Rectangle { constructor(height, width) { this.name = "Rectangle"; this.height = height; this.width = width; } sayName() { console.log("Hi, I am a ", this.name + "."); } get area() { return this.height \* this.width; } set area(value) { this.area = value; } } class Square extends Rectangle { constructor(length) { this.height; // ReferenceError, super needs to be called first! // Here, it calls the parent class's constructor with lengths // provided for the Rectangle's width and height super(length, length); // Note: In derived classes, super() must be called before you // can use 'this'. Leaving this out will cause a reference error. this.name = "Square"; } } ``` ### Super-calling 靜態方法 你也可以使用在靜態方法. ```js class Rectangle { constructor() {} static logNbSides() { return "I have 4 sides"; } } class Square extends Rectangle { constructor() {} static logDescription() { return super.logNbSides() + " which are all equal"; } } Square.logDescription(); // 'I have 4 sides which are all equal' ``` ### 刪除 super 屬性將拋出錯誤 你不能使用 delete operator 以及 `super.prop` 以及 `super[expr]` 去刪除父層的類別屬性, 不然他會丟出一個錯誤 `ReferenceError` (en-US). ```js class Base { constructor() {} foo() {} } class Derived extends Base { constructor() {} delete() { delete super.foo; // this is bad } } new Derived().delete(); // ReferenceError: invalid delete involving 'super'. ``` ### `super.prop` 不能複寫在不能複寫的屬性 當定義不可寫屬性,例如 `Object.defineProperty`, `super` 不能複寫這個屬性的值. ```js class X { constructor() { Object.defineProperty(this, "prop", { configurable: true, writable: false, value: 1, }); } } class Y extends X { constructor() { super(); } foo() { super.prop = 2; // Cannot overwrite the value. } } var y = new Y(); y.foo(); // TypeError: "prop" is read-only console.log(y.prop); // 1 ``` ### 使用 `super.prop` 在對象符號 Super 可以使用在 object initializer / literal (en-US) 符號. 在這個範例, 有兩個對象定義在一個方法. 在第二個對象裡面, `super` 呼叫了第一個對象的方法. 這個動作幫助 `Object.setPrototypeOf()` (en-US) 讓我們可以設定原型 `obj2` to `obj1`, 所以 `super` 可以發現 `method1` 在 `obj1`裡被找到. ```js var obj1 = { method1() { console.log("method 1"); }, }; var obj2 = { method2() { super.method1(); }, }; Object.setPrototypeOf(obj2, obj1); obj2.method2(); // logs "method 1" ``` 規格 -- | Specification | | --- | | ECMAScript Language Specification # sec-super-keyword | Browser compatibility --------------------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參考 -- * Classes * Anurag Majumdar - Super & Extends in JavaScript
this - JavaScript
this ==== JavaScript **函式內的 `this` 關鍵字**表現,和其他語言相比略有差異。在嚴格模式 (en-US)與非嚴格模式下也有所不同。 通常,`this` 值由被呼叫的函式來決定。它不能在執行期間被指派,每次函式呼叫調用的值也可能不同。ES5 引入了 `bind` 方法去設置函式的 `this` 值,而不管它怎麼被呼叫。ECMAScript 2015 也導入了定義 `this` 詞法範圍的箭頭函式(它的 `this` 值會維持在詞法作用域)。 嘗試一下 ---- 語法 -- ```js this ``` 全域環境下 ----- `this` 值在所有函式以外的全域執行環境下,會被當作全域物件,無論是否處於嚴格模式。 ```js console.log(this.document === document); // true // 在網路瀏覽器中,window 物件也是全域物件。 console.log(this === window); // true this.a = 37; console.log(window.a); // 37 this.b = "MDN"; console.log(window.b); // "MDN" console.log(b); // "MDN" ``` 函式環境下 ----- 在函式內的 `this` 值取決於該函式如何被呼叫。 ### 簡易呼叫 因為以下程式碼並不處於嚴謹模式下、而 `this` 值也沒被呼叫(call)設定,`this` 會變成全域物件,在瀏覽器之下則會變成 `window`。 ```js function f1() { return this; } //在瀏覽器中: f1() === window; // true //Node中: f1() === global; // true ``` 然而,在嚴格模式下,`this` 值會在進入執行環境時建立並維持該狀態。因此,下例的 `this` 預設值是 `undefined`: ```js function f2() { "use strict"; // 嚴格模式 return this; } f2() === undefined; //true ``` 所以在嚴格模式下,如果 `this` 沒有定義到執行環境內,其預設值就會是 `undefined`。 **備註:** 在第二個例子裡面,`this` 應為 `undefined` (en-US),因為 `f2` 是直接被呼叫,而不是在其為某個物件的方法或屬性的情況下(例如 `window.f2()`)被直接呼叫。某些瀏覽器首次支援嚴格模式 (en-US)時沒導入這個特徵,它們會因此錯誤的回傳 `window` 物件。 要從某個語境訪問另一個 `this` 語境的值,請使用 call 或 apply: ```js // 物件可以被當作call或apply的第一個參數,而this會綁定該物件 var obj = { a: "Custom" }; // 此屬性a為全域物件 var a = "Global"; function whatsThis(arg) { return this.a; // this 值取決於此函數如何被呼叫 } whatsThis(); // 'Global' whatsThis.call(obj); // 'Custom' whatsThis.apply(obj); // 'Custom' ``` 當函式內部調用 `this` 關鍵字時,其值會和所有繼承自 `Function.prototype` 並使用 `call` 或 `apply` 方法呼叫的特定物件綁定。 ```js function add(c, d) { return this.a + this.b + c + d; } var o = { a: 1, b: 3 }; // 第一個參數(parameter)是調用了 this 的物件, // 後續參數(parameters)會作為函式呼叫內的參數(arguments)而通過 add.call(o, 5, 7); // 16 // 第一個參數(parameter)是調用了 this 的物件, // 第二個參數的陣列作為函式呼叫內的參數(arguments)之構件 add.apply(o, [10, 20]); // 34 ``` 使用 `call` 和 `apply` 時,如果被輸入作為 `this` 的值不是物件,JavaScript 內建的 `ToObject` 運算符會試著把被輸入的值轉變為物件。如果被輸入的值是一個原始型別,例如 `7`或是 `'foo'`,它們會自動被相關的建構方法轉變為物件。因此,原始數值`7`會轉變成類似用`new Number(7)`產生的物件,而字串`'foo'`會轉變成類似用`new String('foo')`產生的物件。 ```js function bar() { console.log(Object.prototype.toString.call(this)); } bar.call(7); // [object Number] bar.call("foo"); // [Object String] ``` ### `bind` 方法 ECMAScript 5 導入了 `Function.prototype.bind`。呼叫 `f.bind(someObject)` 會建立和 `f` 的主體與作用域相同之新函式;但無論函數怎麼被調用,原始函數的 `this` 在新函數將永遠與 `bind` 的第一個參數綁定起來。 ```js function f() { return this.a; } var g = f.bind({ a: "azerty" }); console.log(g()); // azerty var h = g.bind({ a: "yoo" }); // bind 只能使用一次! console.log(h()); // azerty var o = { a: 37, f: f, g: g, h: h }; console.log(o.f(), o.g(), o.h()); // 37, azerty, azerty ``` ### 箭頭函式 在箭頭函式下,`this` 值保留了其在詞法作用域 的 `this` 值。在全域程式碼內,則設為全域物件: ```js var globalObject = this; var foo = () => this; console.log(foo() === globalObject); // true ``` **備註:** 如果這參數被傳遞給箭頭函式的 call, bind, apply 調用,該參數會被忽略。你仍然可以將參數預先調用到 call,但第一個參數(thisArg)必須設置為空。 ```js // 作為物件的方法呼叫 var obj = { foo: foo }; console.log(obj.foo() === globalObject); // true // 使用呼叫以嘗試設置 this console.log(foo.call(obj) === globalObject); // true // 使用 bind 以嘗試設置 this foo = foo.bind(obj); console.log(foo() === globalObject); // true ``` 無論以上哪種,`foo` 的 `this` 在建立的時候,都會設為原本的樣子(以上面的例子來說,就是全域物件)。這同樣適用於在其他函式內創建的箭頭函式:它們的 `this` 是設置為外部執行上下文。 ```js // 建立一個物件,其方法 bar 含有回傳自己的 this 函式。回傳函式作為箭頭函數而建立, // 因此該函式的 this 將永遠與外圍函式(enclosing function)的 this 綁定。 // bar 的值可在呼叫內設立,which in turn sets the value of the returned function. var obj = { bar: function () { var x = () => this; return x; }, }; // 將 bar 作為物件的方法呼叫,把它的 this 設為物件 // 指派 fn 作為回傳函數的參照(reference) var fn = obj.bar(); // 在不設置 this 情況下呼叫的 fn,通常默認為全域物件,在嚴格模式下則是 undefined console.log(fn() === obj); // true ``` 以上面的程式碼為例,稱作匿名函數(anonymous function)A 的函數被指定為 `obj.bar`,它回傳的函數(稱作匿名函數 B)作為箭頭函數而建立。因而,函數 B 的 `this` 在呼叫時,將永遠設為 `obj.bar` (函數 A)的 `this`。呼叫被回傳的函數(函數 B)時,它的 `this` 將一直是原本的樣子。 再以上面的程式碼為例,函數 B 的 `this` 被設為函數 A 的 `this`,而它屬於物件,所以它依然會設為 `obj`,就算在 `this` 設為 `undefined` 或全域物件的呼叫方式下(或在全域執行環境下,上例的任何方法) ### 作為物件方法 如果一個函式是以物件的方法呼叫,它的 `this` 會設為該呼叫函式的物件。 以下面的程式碼為例,呼叫 `o.f()` 的時候,函式內的 `this` 會和 `o` 物件綁定。 ```js var o = { prop: 37, f: function () { return this.prop; }, }; console.log(o.f()); // logs 37 ``` 請注意這個行為,不會受函式如何或何處定義所影響。以上面為例,在我們定義 `o` 時,也定義了行內函式 `f` 作為構件(member)。不過,我們也能先定義函式,接著讓它附屬到 `o.f`。這麼做會得出相同的效果: ```js var o = { prop: 37 }; function independent() { return this.prop; } o.f = independent; console.log(o.f()); // 37 ``` 這表明了 `this` 只和 `f` 作為 `o` 的構件呼叫有所關聯。 同樣的,`this` 綁定只會受最直接的構件引用(most immediate member reference)所影響。在下面的例子,我們將物件 `o.b` 的方法 `g` 作為函式呼叫。在執行的期間,函式內的 `this` 會參照 `o.b`。物件是否為 `o` 的構件無關緊要,最直接的引用才是最緊要的。 ```js o.b = { g: independent, prop: 42 }; console.log(o.b.g()); // logs 42 ``` #### 物件原型鏈上的 `this` 相同概念也能套用定義物件原型鏈的方法。如果方法放在物件的原型鏈上,`this` 會指向方法所呼叫的物件,如同該方法在物件上的樣子。 ```js var o = { f: function () { return this.a + this.b; }, }; var p = Object.create(o); p.a = 1; p.b = 4; console.log(p.f()); // 5 ``` 在這個示例中,分配給變數 `p` 的物件沒有自己的 `f` 屬性,`p` 繼承了 `o` 的原型。但是查找 `f` 最終在 `o`上找到它的成員名為 f 並不重要。查找開始作為 `p.f` 的引用,所以 `this` 在函式內部物件的值被當作是`p`的引用。也就是說,`f` 作為 `p`的調用方法以來,它的 `this` 指的就是 `p`。這是一個非常有趣的 JavaScript 原型繼承特性。 #### 帶著 getter 或 setter 的 `this` 當函式從 getter 或 setter 被調用的時候,同樣的概念也成立。用作 getter 或 setter 的函式將自己的 `this` 綁定到從中設置或獲取的物件上。 ```js function sum() { return this.a + this.b + this.c; } var o = { a: 1, b: 2, c: 3, get average() { return (this.a + this.b + this.c) / 3; }, }; Object.defineProperty(o, "sum", { get: sum, enumerable: true, configurable: true, }); console.log(o.average, o.sum); // logs 2, 6 ``` ### 作為建構子 若函式以建構子的身份呼叫(使用 `new` 關鍵字) `this` 會和被建構的新物件綁定。 **備註:** 建構子預設透過 `this` 回傳該物件的參照,但它其實能回傳其他物件。如果回傳值不是物件的話,就會回傳 `this` 這個物件。 ```js /\* \* 建構子會如此做動: \* \* function MyConstructor(){ \* // 實際的函式主體碼在這裡 \* // 在|this| 上創建屬性 \* // 希望通過分配給他們,如: \* this.fum = "nom"; \* // et cetera... \* \* // 如果函式有返回狀態它將返回一個物件 \* // 那個物件將是新表達式的結果。 \* // 換句話來說,表達式的結果是現在綁定 |this| 的物件 \* // (例如,最常見的常見情況). \* } \*/ function C() { this.a = 37; } var o = new C(); console.log(o.a); // logs 37 function C2() { this.a = 37; return { a: 38 }; } o = new C2(); console.log(o.a); // logs 38 ``` 在上例的 `C2`,由於物件在建構的時候被呼叫,新的物件 `this` was bound to simply gets discarded。這也實質上令 `this.a = 37;` 宣告死亡:不是真的死亡(因為已經執行了),但它在毫無 outside effects 的情況下遭到消滅。 ### 作為 DOM 事件處理器 當一個函式用作事件處理器的話,`this` 值會設在觸發事件的元素(某些瀏覽器如果不用 `addEventListener` 方法的話,在動態添加監聽器時,就不會遵循這個常規) ```js // 當監聽器被調用,相關元素變為藍色 function bluify(e) { // 永遠是真 console.log(this === e.currentTarget); // 當當前目標和目標為相同物件為真 console.log(this === e.target); this.style.backgroundColor = "#A5D9F3"; } // 取得文件內所有的元素 var elements = document.getElementsByTagName("\*"); // Add bluify as a click listener so when the // element is clicked on, it turns blue for (var i = 0; i < elements.length; i++) { elements[i].addEventListener("click", bluify, false); } ``` ### 作為行內事件處理器 當程式碼從行內的 on 事件處理器呼叫的話,`this` 就會設在監聽器所置的 DOM 元素: ```html <button onclick="alert(this.tagName.toLowerCase());">Show this</button> ``` 上方的 alert 會秀出 `button`。但請注意只有外層程式碼的 `this` 要這樣設定: ```html <button onclick="alert((function(){return this})());">Show inner this</button> ``` 在這裡,內部函式的並沒有設立 `this`,所以它會回傳全域/window 物件(例如在非嚴格模式下,呼叫函數沒設定 `this` 的預設物件) 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-this-keyword | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * 嚴格模式 (en-US) * All this,一篇關於 `this` 上下文不同的相關文章 * 親和地解釋 JavaScript 的「this」關鍵字
遞增運算子(++) - JavaScript
遞增運算子(++) ========= 遞增運算子(`++`)遞增(加一)它的運算元並將結果回傳。 嘗試一下 ---- 語法 -- ```js x++ ++x ``` 詳細說明 ---- 若將遞增運算子作為後綴(例如 `x++`),則會先回傳原本的值,再進行遞增。 若作為前綴(例如 `++x`),則會先進行遞增,再將遞增後的結果回傳。 範例 -- ### 遞增運算子置於後綴 ```js let x = 3; y = x++; // y = 3 // x = 4 ``` ### 遞增運算子置於前綴 ```js let a = 2; b = ++a; // a = 3 // b = 3 ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-postfix-increment-operator | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * 相加運算子 * 相減運算子 * 相除運算子 * 餘數運算子 (en-US) * 相乘運算子 * 指數運算子 * 遞減運算子 * 負號運算子 * 正號運算子
屬性的刪除 - JavaScript
屬性的刪除 ===== 你可以使用 `delete` 運算子移除屬性。下面的代碼示範如何移除屬性︰ ```js // 建立新的物件 myobj,以及兩個屬性 a 和 b。 myobj = new Object(); myobj.a = 5; myobj.b = 12; // 移除一個屬性,只剩 b 屬性留在 myobj 裡。 delete myobj.a; ``` 你也可以使用 `delete` 來刪除全域變數,只要這個變數不是使用 `var` 關鍵字宣告的話︰ ```js g = 17; delete g; ``` 參閱 delete 取得更多資訊。 * « 前頁 * 次頁 »
遞減運算子(--) - JavaScript
遞減運算子(--) ========= 遞減運算子(`--`)遞減(減一)它的運算元並將結果回傳。 嘗試一下 ---- 語法 -- ```js x-- --x ``` 詳細說明 ---- 若將遞減運算子作為後綴(例如 `x--`),則會先回傳原本的值,在進行遞減。 若作為前綴(例如 `--x`),則會先進行遞減,在將遞減後的結果回傳。 範例 -- ### 遞減運算子置於後綴 ```js let x = 3; y = x--; // y = 3 // x = 2 ``` ### 遞減運算子置於前綴 ```js let a = 2; b = --a; // a = 1 // b = 1 ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-postfix-decrement-operator | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * 相加運算子 * 相減運算子 * 相除運算子 * 餘數運算子 (en-US) * 相乘運算子 * 指數運算子 * 遞增運算子 * 負號運算子 * 正號運算子
相減運算子(-) - JavaScript
相減運算子(-) ======== 相減運算子(`-`)是用來將兩個值進行相減,並得出它們的差值。 嘗試一下 ---- 語法 -- ```js x - y ``` 範例 -- ### 數字相減 ```js 5 - 3; // 2 3 - 5; // -2 ``` ### 非數字之間的相減 ```js "foo" - 3; // NaN ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-subtraction-operator-minus | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * 相加運算子 * 相除運算子 * 相乘運算子 * 餘數運算子 (en-US) * 指數運算子 * 遞增運算子 * 遞減運算子 * 負號運算子 * 正號運算子
相乘運算子(*) - JavaScript
相乘運算子(\*) ========= 相乘運算子(`*`)是用來取得兩個運算元的乘積。 嘗試一下 ---- 語法 -- ```js x \* y ``` 範例 -- ### 乘以數字 ```js 2 \* 2; // 4 -2 \* 2; // -4 ``` ### 乘以無限(Infinity) ```js Infinity \* 0; // NaN Infinity \* Infinity; // Infinity ``` ### 乘以非數字 ```js "foo" \* 2; // NaN ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-multiplicative-operators | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * 相加運算子 * 相減運算子 * 相除運算子 * 餘數運算子 (en-US) * 指數運算子 * 遞增運算子 * 遞減運算子 * 負號運算子 * 正號運算子
解構賦值 - JavaScript
解構賦值 ==== **解構賦值** (Destructuring assignment) 語法是一種 JavaScript 運算式,可以把陣列或物件中的資料解開擷取成為獨立變數。 嘗試一下 ---- 語法 -- ```js let a, b, rest; [a, b] = [10, 20]; console.log(a); // 10 console.log(b); // 20 [a, b, ...rest] = [10, 20, 30, 40, 50]; console.log(a); // 10 console.log(b); // 20 console.log(rest); // [30, 40, 50] ({ a, b } = { a: 10, b: 20 }); console.log(a); // 10 console.log(b); // 20 // Stage 4(finished) proposal ({ a, b, ...rest } = { a: 10, b: 20, c: 30, d: 40 }); console.log(a); // 10 console.log(b); // 20 console.log(rest); // {c: 30, d: 40} ``` 描述 -- 物件與陣列運算式提供了簡單的方式,建立特定的資料組。 ```js const x = [1, 2, 3, 4, 5]; ``` 解構賦值使用類似語法;不過在指定敘述式的左側,要宣告從來源變數接收解開值之變數。 ```js const x = [1, 2, 3, 4, 5]; const [y, z] = x; console.log(y); // 1 console.log(z); // 2 ``` Perl 和 Python 也有類似的語法和功能。 陣列解構 ---- ### 基本變數指定敘述 ```js const foo = ["one", "two", "three"]; const [red, yellow, green] = foo; console.log(red); // "one" console.log(yellow); // "two" console.log(green); // "three" ``` ### 宣告指派分開敍述 變數可以在宣告式後,再透過解構賦值。 ```js let a, b; [a, b] = [1, 2]; console.log(a); // 1 console.log(b); // 2 ``` ### 預設值 當解構來源陣列對應的元素是 undefined 時,變數可以被設定預設值。 ```js let a, b; [a = 5, b = 7] = [1]; console.log(a); // 1 console.log(b); // 7 ``` ### 變數交換 兩個變數可以透過一個解構指派式交換。 沒有解構指派式時,這需要一個暫存變數來達成(或者像某些低階語言的 XOR-swap trick)。 ```js let a = 1; let b = 3; [a, b] = [b, a]; console.log(a); // 3 console.log(b); // 1 const arr = [1, 2, 3]; [arr[2], arr[1]] = [arr[1], arr[2]]; console.log(arr); // [1,3,2] ``` ### 解析自函式回傳的陣列 一直以來函式都可以回傳陣列,而解構指派式可以讓回傳的值更加簡潔。 在這個例子, `f()` 回傳 `[1, 2]` ,接著透過一個解構指派式解析。 ```js function f() { return [1, 2]; } let a, b; [a, b] = f(); console.log(a); // 1 console.log(b); // 2 ``` ### 忽略某些回傳值 你可以忽略某些回傳值: ```js function f() { return [1, 2, 3]; } const [a, , b] = f(); console.log(a); // 1 console.log(b); // 3 ``` 當然你也可以忽略全部回傳值: ```js [, ,] = f(); ``` ### 把矩陣剩餘部分解構到一個變數 解構一個陣列時,你可以透過其餘元素(rest pattern)將來源剩下之元素指派到一個變數: ```js const [a, ...b] = [1, 2, 3]; console.log(a); // 1 console.log(b); // [2, 3] ``` 要注意的是,當左邊函式裡使用其餘解構,同時使用結尾逗號,這樣會拋出例外 `SyntaxError` (en-US) : ```js const [a, ...b,] = [1, 2, 3]; // SyntaxError 語法錯誤: 其餘元素不可以跟隨結尾逗號 // 需要把其餘運算子放在最後的元素 ``` ### 從正則運算式的比對結果取值 當正則運算式的方法 `exec()` (en-US) 比對到一個值,其回傳陣列中的第一個值是相符的完整字串,後績的則是比對到正則運算式每組括號內的部分。當你沒需要利用第一個完整比對結果時,解構指派式讓你更簡單的取出後績元素。 ```js function parseProtocol(url) { const parsedURL = /^(\w+)\:\/\/([^\/]+)\/(.\*)$/.exec(url); if (!parsedURL) { return false; } console.log(parsedURL); // ["https://developer.mozilla.org/en-US/Web/JavaScript", "https", "developer.mozilla.org", "en-US/Web/JavaScript"] const [, protocol, fullhost, fullpath] = parsedURL; return protocol; } console.log( parseProtocol("https://developer.mozilla.org/en-US/Web/JavaScript"), ); // "https" ``` 物件解構 ---- ### 基本指派式 ```js const o = { p: 42, q: true }; const { p, q } = o; console.log(p); // 42 console.log(q); // true ``` ### 無宣告指派 變數可以在宣告式後,再透過解構進行指派。 ```js let a, b; ({ a, b } = { a: 1, b: 2 }); ``` **備註:** 當針對物件進行解構,而該句式沒有進行宣告時,指派式外必須加上括號 `( ... )` 。 `{a, b} = {a: 1, b: 2}` 不是有效的獨立語法,因為左邊的 `{a, b}` 被視為程式碼區塊而非物件。 然而,`({a, b} = {a: 1, b: 2})` 是有效的,如同 `const {a, b} = {a: 1, b: 2}` `( ... )` 表達式前句需要以分號結束,否則可能把上一句視為函式隨即執行。 ### 指派到新的變數名稱 物件中的屬性可以解構並擷取到名稱跟該屬性不一樣的變數。 ```js const o = { p: 42, q: true }; const { p: foo, q: bar } = o; console.log(foo); // 42 console.log(bar); // true ``` 舉例來說, `const {p: foo} = o` 把物件 `o` 裡名為 `p` 的屬性解出並指派到一個名為 `foo` 的本地變數。 ### 預設值 當解構物件中對應的值是 `undefined` 時,變數可以設定預設值。 ```js const { a = 10, b = 5 } = { a: 3 }; console.log(a); // 3 console.log(b); // 5 ``` ### 指定新的變數名稱及預設值 屬性 1) 可以從物件中被解開,且被指定一個不同名稱的變數及 2) 同時指定一個預設值,在解開的值為 `undefined` 時使用。 ```js const { a: aa = 10, b: bb = 5 } = { a: 3 }; console.log(aa); // 3 console.log(bb); // 5 ``` ### 從作為函式參數的物件中提出某屬性的值 ```js const user = { id: 42, displayName: "jdoe", fullName: { firstName: "John", lastName: "Doe", }, }; function userId({ id }) { return id; } function whois({ displayName, fullName: { firstName: name } }) { return `${displayName} is ${name}`; } console.log(userId(user)); // 42 console.log(whois(user)); // "jdoe is John" ``` 這樣從 user 物件中提出了 `id`, `displayName` 和 `firstName` 並且印出。 ### 設定函式參數的預設值 ```js function drawChart({ size = "big", coords = { x: 0, y: 0 }, radius = 25, } = {}) { console.log(size, coords, radius); // do some chart drawing } drawChart({ coords: { x: 18, y: 30 }, radius: 30, }); ``` **備註:** 在上述函式 **`drawChart`** 中,左方之解構式被指派到一個空物件: `{size = 'big', coords = {x: 0, y: 0}, radius = 25} = {}` 。你也可以略過填寫右方的指派式。不過,當你沒有使用右方指派式時,函式在呼叫時會找出最少一個參數。透過上述形式,你可以直接不使用參數的呼叫 **`drawChart()`** 。當你希望在呼叫這個函式時不傳送參數,這個設計會帶來方便。而另一個設計則能讓你確保函式必須傳上一個物件作為參數。 ### 巢狀物件或陣列的解構 ```js const metadata = { title: "Scratchpad", translations: [ { locale: "de", localization\_tags: [], last\_edit: "2014-04-14T08:43:37", url: "/de/docs/Tools/Scratchpad", title: "JavaScript-Umgebung", }, ], url: "/zh-TW/docs/Tools/Scratchpad", }; let { title: englishTitle, // rename translations: [ { title: localeTitle, // rename }, ], } = metadata; console.log(englishTitle); // "Scratchpad" console.log(localeTitle); // "JavaScript-Umgebung" ``` ### 循環取出的解構 ```js const people = [ { name: "Mike Smith", family: { mother: "Jane Smith", father: "Harry Smith", sister: "Samantha Smith", }, age: 35, }, { name: "Tom Jones", family: { mother: "Norah Jones", father: "Richard Jones", brother: "Howard Jones", }, age: 25, }, ]; for (const { name: n, family: { father: f }, } of people) { console.log("Name: " + n + ", Father: " + f); } // "Name: Mike Smith, Father: Harry Smith" // "Name: Tom Jones, Father: Richard Jones" ``` ### 以物件演算屬性名稱解構 物件演算屬性名稱(像是在 object literals (en-US))可以在解構指派式使用。 ```js let key = "z"; let { [key]: foo } = { z: "bar" }; console.log(foo); // "bar" ``` ### 在物件解構時使用其餘變數 ECMAScript 中的其餘/展開屬性在 proposal (stage 4) 新增了在解構式內使用其餘 (rest) 語法的定義。其餘屬性可以收集解構式中沒有指定的屬性值。 ```js let { a, b, ...rest } = { a: 10, b: 20, c: 30, d: 40 }; a; // 10 b; // 20 rest; // { c: 30, d: 40 } ``` ### 不符合 JavaScript 識別字的屬性名稱 解構賦值可以透過另一個符合 JavaScript 識別字的變數名稱來解出不符合識別字的屬性。 ```js const foo = { "fizz-buzz": true }; const { "fizz-buzz": fizzBuzz } = foo; console.log(fizzBuzz); // "true" ``` ### 混合使用矩陣及物件解構 矩陣及物件解構可以混合進行。與例來說,你只需要使用下列 `props` 矩陣中第三個元素之物件中的 `name` 屬性,你可以如下面的例子進行解構: ```js const props = [ { id: 1, name: "Fizz" }, { id: 2, name: "Buzz" }, { id: 3, name: "FizzBuzz" }, ]; const [, , { name }] = props; console.log(name); // "FizzBuzz" ``` ### 物件解構時的原型鏈追溯 在進行物件解構時,如果一個屬性不在其當下存取,將會透過原型鏈 (prototype chain) 來進行追溯。 ``` let obj = {self: '123'}; obj.__proto__.prot = '456'; const {self, prot} = obj; // self "123" // prot "456"(Access to the prototype chain) ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-destructuring-assignment | | ECMAScript Language Specification # sec-destructuring-binding-patterns | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * Assignment operators (en-US) * "ES6 in Depth: Destructuring" on hacks.mozilla.org
相加運算子(+) - JavaScript
相加運算子(+) ======== 相加運算子(`+`)用來處理數字的相加或是進行字串的串聯。 嘗試一下 ---- 語法 -- ```js x + y ``` 範例 -- ### 數字相加 ```js // Number + Number -> addition 1 + 2; // 3 // Boolean + Number -> addition true + 1; // 2 // Boolean + Boolean -> addition false + false; // 0 ``` ### 字串串聯 ```js // String + String -> concatenation "foo" + "bar"; // "foobar" // Number + String -> concatenation 5 + "foo"; // "5foo" // String + Boolean -> concatenation "foo" + false; // "foofalse" ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-addition-operator-plus | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * 相減運算子 * 相除運算子 * 相乘運算子 * 餘數運算子 (en-US) * 指數運算子 * 遞增運算子 * 遞減運算子 * 負號運算子 * 正號運算子
await - JavaScript
await ===== Baseline Widely available ------------------------- This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2017. * Learn more * See full compatibility * Report feedback await 運算子可被用來等待 `Promise`,只能在 `async function`內使用。語法 -- ``` [rv] = await expression; ``` `expression` 等待解析的 `Promise` 物件或任何值。 `rv = 回傳值` 回傳 Promise 物件的 resolved 值,或當該值不是 Promise 物件時,回傳該值本身。 描述 -- 此 await 表示法會暫停 async 函式執行,等待 Promise 物件的解析,並在 promise 物件的值被 resolve 時回復 async 函式的執行。await 接著回傳這個被 resolve 的值。如果回傳值不是一個 Promise 物件,則會被轉換為 resolved 狀態的 Promise 物件。 如果 Promise 物件被 rejected,則 await 會丟出 rejected 的值。 範例 -- 若將 Promise 物件傳給 await 運算式,它會等待 Promise 解析並回傳 resolve 後的值。 ```js function resolveAfter2Seconds(x) { return new Promise((resolve) => { setTimeout(() => { resolve(x); }, 2000); }); } async function f1() { var x = await resolveAfter2Seconds(10); console.log(x); // 10 } f1(); ``` 若傳給 await 的值並非一個 Promise 物件,它會將該值轉換為 resolved Promise,並等待之。 ```js async function f2() { var y = await 20; console.log(y); // 20 } f2(); ``` 若 Promise 被 reject,則丟出 reject 後的異常值。 ```js async function f3() { try { var z = await Promise.reject(30); } catch (e) { console.log(e); // 30 } } f3(); ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-async-function-definitions | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. See also -------- * `async function` * `async function expression` (en-US) * `AsyncFunction` (en-US) object
運算子優先序 - JavaScript
運算子優先序 ====== 運算子優先序(Operator precedence)決定了運算子彼此之間被語法解析的方式,優先序較高的運算子會成為優先序較低運算子的運算元(operands)。 嘗試一下 ---- 相依性(Associativity) ------------------ 當優先序相同時,使用相依性決定運算方向。範例如下: ``` a OP b OP c ``` 左相依性 (Left-associativity) ,表示處理順序為從左至右 `(a OP b) OP c`,反之,右相依性(right-associativity) 表示處理順序為從右至左 `a OP (b OP c)`。賦值運算符 (Assignment operators) 為右相依性,範例如下: ```js a = b = 5; ``` `a` 和 `b` 的預期結果為 5,因為賦值運算符 (Assignment operator) 為右相依性,因此從右至左返回值。一開始 `b` 被設定為 5,接著 `a` 也被設定為 5。 表格(Table) --------- 下方表格列出運算子的相依性,從高 (19) 到低 (1)。 | 優先性Precedence | 運算子名稱Operator type | 相依性Associativity | 運算子Individual operators | | --- | --- | --- | --- | | 19 | Grouping (en-US) | 無 | `( … )` | | 18 | Member Access (en-US) | 從左至右 | `… . …` | | Computed Member Access (en-US) | 從左至右 | `… [ … ]` | | `new` (with argument list) | 無 | `new … ( … )` | | 呼叫函式 | 從左至右 | `… ( … )` | | 可選串連(Optional chaining) | 從左至右 | `?.` | | 17 | `new` (without argument list) | 從右至左 | `new …` | | 16 | 字尾遞增 | 無 | `… ++` | | 字尾遞減 | `… --` | | 15 | Logical NOT (en-US) | 從右至左 | `! …` | | Bitwise NOT (en-US) | `~ …` | | Unary Plus | `+ …` | | Unary Negation | `- …` | | 字首遞增 | `++ …` | | 字首遞減 | `-- …` | | `typeof` | `typeof …` | | `void` (en-US) | `void …` | | `delete` | `delete …` | | `await` | `await …` | | 14 | Exponentiation | 從右至左 | `… ** …` | | 13 | Multiplication | 從左至右 | `… * …` | | Division | `… / …` | | Remainder (en-US) | `… % …` | | 12 | Addition | 從左至右 | `… + …` | | Subtraction | `… - …` | | 11 | Bitwise Left Shift (en-US) | 從左至右 | `… << …` | | Bitwise Right Shift (en-US) | `… >> …` | | Bitwise Unsigned Right Shift (en-US) | `… >>> …` | | 10 | Less Than (en-US) | 從左至右 | `… < …` | | Less Than Or Equal (en-US) | `… <= …` | | Greater Than (en-US) | `… > …` | | Greater Than Or Equal (en-US) | `… >= …` | | `in` (en-US) | `… in …` | | `instanceof` (en-US) | `… instanceof …` | | 9 | Equality (en-US) | 從左至右 | `… == …` | | Inequality (en-US) | `… != …` | | Strict Equality (en-US) | `… === …` | | Strict Inequality (en-US) | `… !== …` | | 8 | Bitwise AND (en-US) | 從左至右 | `… & …` | | 7 | Bitwise XOR (en-US) | 從左至右 | `… ^ …` | | 6 | Bitwise OR (en-US) | 從左至右 | `… | …` | | 5 | Logical AND (en-US) | 從左至右 | `… && …` | | 4 | Logical OR (en-US) | 從左至右 | `… || …` | | Nullish Coalescing (en-US) | 從左至右 | `… ?? …` | | 3 | 條件運算 | 從右至左 | `… ? … : …` | | 2 | 賦值 | 從右至左 | `… = …` | | `… += …` | | `… -= …` | | `… **= …` | | `… *= …` | | `… /= …` | | `… %= …` | | `… <<= …` | | `… >>= …` | | `… >>>= …` | | `… &= …` | | `… ^= …` | | `… |= …` | | `… &&= …` | | `… ||= …` | | `… ??= …` | | 1 | Comma / Sequence (en-US) | 從左至右 | `… , …` |
一元負號運算子(-) - JavaScript
一元負號運算子(-) ========== 一元負號運算子(`-`)置於運算元之前,並將運算元轉為其負值。 嘗試一下 ---- 語法 -- ```js -x ``` 範例 -- ### 轉換數字 ```js const x = 3; const y = -x; // y = -3 // x = 3 ``` ### 轉換非數字 一元負號運算子可以將非數字轉為數字。 ```js const x = "4"; const y = -x; // y = -4 ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-unary-minus-operator | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * 相加運算子 * 相減運算子 * 相除運算子 * 相乘運算子 * 餘數運算子 (en-US) * 相乘運算子 * 指數運算子 * 遞減運算子 * 正號運算子
typeof - JavaScript
typeof ====== 摘要 -- typeof 運算子會傳回一個字串值, 指出未經運算 (unevaluated) 的運算元所代表的型別。 | 運算子 | | --- | | 實作於: | JavaScript 1.1 | | ECMA 版本: | ECMA-262 (以及 ECMA-357 for E4X objects) | 語法 -- `typeof` 之後面跟著它的唯一運算元: ``` typeof operand ``` 參數 -- `operand` 表示式代表傳入的物件或原始型別。 說明 -- 下表摘要列出了 `typeof 可能的傳回值`: | 型別 | 傳回 | | --- | --- | | Undefined | `"undefined"` | | Null | `"object"` | | Boolean | `"boolean"` | | Number | `"number"` | | String | `"string"` | | 主機端物件 (由 JS 執行環境提供) | *視實作方式而異* | | Function 物件 (實作 ECMA-262 所定義的 [[Call]]) | `"function"` | | E4X XML 物件 | "xml" | | E4X XMLList 物件 | "xml" | | 所有其它物件 | `"object"` | 範例 -- ### 一般情況 ```js // Numbers typeof 37 === "number"; typeof 3.14 === "number"; typeof Math.LN2 === "number"; typeof Infinity === "number"; typeof NaN === "number"; // 雖然是 "Not-A-Number" typeof Number(1) === "number"; // 但是不要使用這種方式! // Strings typeof "" === "string"; typeof "bla" === "string"; typeof typeof 1 === "string"; // typeof 一律會傳回一個字串 typeof String("abc") === "string"; // 但是不要使用這種方式! // Booleans typeof true === "boolean"; typeof false === "boolean"; typeof Boolean(true) === "boolean"; // 但是不要使用這種方式! // Undefined typeof undefined === "undefined"; typeof blabla === "undefined"; // 一個 undefined 變數 // Objects typeof { a: 1 } === "object"; typeof [1, 2, 4] === "object"; // 請使用 Array.isArray 或者 Object.prototype.toString.call 以區分正規運算式和陣列 typeof new Date() === "object"; typeof new Boolean(true) === "object"; // 這樣會令人混淆。不要這樣用! typeof new Number(1) === "object"; // 這樣會令人混淆。不要這樣用! typeof new String("abc") === "object"; // 這樣會令人混淆。不要這樣用! // Functions typeof function () {} === "function"; typeof Math.sin === "function"; ``` ### `null` ```js typeof null === "object"; // 自從有 JavaScript 開始就是這樣了 ``` 自從 JavaScript 一開始出現, JavaScript 的值就總以型別標簽跟著一個值的方式表示。物件的型別標簽是 0. 而 `null` 這個值是使用 NULL 指標 (在大部份平台上是 0x00) 來表示. 因此, null 看起來像是一個以 0 為型別標簽的值, 並使得 `typeof` 傳回不甚正確的結果. (參考來源) 這個問題已計畫在下一版 ECMAScript 予以修正 (會以 opt-in 方式提供). 屆時它將會做出如 `typeof null === 'null'` 的正確回傳結果。 **備註:** 此修正計畫已被拒絕 ### 正規表示式 (Regular expressions) 可呼叫的正規表示式在某些瀏覽器上面必須借助非正式插件 (need reference to say which). ```js typeof /s/ === "function"; // Chrome 1-12 ... // 不符合 ECMAScript 5.1 (譯註: 在新版 Chrome 已修正為 'object') typeof /s/ === "object"; // Firefox 5+ ... // 符合 ECMAScript 5.1 ``` ### 其它怪異輸入 (quirks) #### 舊版 Internet Explorer 請留意 alert 函數 在 IE 6, 7 和 8, `typeof alert === 'object'` **備註:** 這並不怪異。這是實情。在許多較舊的 IE 中, 主機端物件的確是物件, 而非函數 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-typeof-operator | 參照 -- * instanceof (en-US)
相除運算子(/) - JavaScript
相除運算子(/) ======== 相除運算子(`/`)是用來將兩個值進行相除並取得其商數。其中左運算元是被除數;右運算元是除數。 嘗試一下 ---- 語法 -- ```js x / y ``` 範例 -- ### 基本的除法 ```js 1 / 2; // 0.5 Math.floor(3 / 2); // 1 1.0 / 2.0; // 0.5 ``` ### 除以零 ```js 2.0 / 0; // Infinity 2.0 / 0.0; // Infinity, because 0.0 === 0 2.0 / -0.0; // -Infinity ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-multiplicative-operators | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * 相加運算子 * 相減運算子 * 相乘運算子 * 餘數運算子 (en-US) * 指數運算子 * 遞增運算子 * 遞減運算子 * 負號運算子 * 正號運算子
條件運算子 - JavaScript
條件運算子 ===== **條件 (三元) 運算子** 是 JavaScript 唯一用到三個運算元的運算子:在一個條件後面會跟著一個問號 (`?`),如果條件是 truthy (en-US),在冒號(`:`)前的表達式會被執行,如果條件是 falsy (en-US),在冒號後面的表達式會被執行,這個運算子常常被用來當作 `if` 的簡潔寫法. 嘗試一下 ---- 語法 -- ``` condition ? exprIfTrue : exprIfFalse ``` ### 參數 `condition` 值用來做為條件的表達式 `exprIfTrue` 如果 `condition` 的值是 truthy (en-US) (等於或是可轉換為 `true`) , `exprIfTrue` 會被執行 `exprIfFalse` 如果 `condition` 的值是 falsy (en-US) (等於或是可轉換為 `false`) , `exprIfFalse` 會被執行 描述 -- 除了 `false`, 可能是 falsy 的表達式有 `null`, `NaN`, `0`, 空字串 (`""`) 和 `undefined`. 如果`condition` 是他們其中之一 , 那麼條件表達式的結果會是 `exprIfFalse` 的執行結果. 一個簡單的範例: ```js var age = 26; var beverage = age >= 21 ? "Beer" : "Juice"; console.log(beverage); // "Beer" ``` 一個常用來處理 `null` 的用法 : ```js function greeting(person) { var name = person ? person.name : "stranger"; return "Howdy, " + name; } console.log(greeting({ name: "Alice" })); // "Howdy, Alice" console.log(greeting(null)); // "Howdy, stranger" ``` ### 條件鏈 條件 (三元) 運算子是右相依性的 (right-associative), 代表他可以以下面的方式鏈結 , 類似於 `if … else if … else if … else` 的鏈結方法 : ```js function example(…) { return condition1 ? value1 : condition2 ? value2 : condition3 ? value3 : value4; } // Equivalent to: function example(…) { if (condition1) { return value1; } else if (condition2) { return value2; } else if (condition3) { return value3; } else { return value4; } } ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-conditional-operator | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * if statement * Nullish coalescing operator (en-US) * Optional chaining * Making decisions in your code — conditionals * Expressions and operators
指數運算子(**) - JavaScript
指數運算子(\*\*) =========== 指數運算子(`**`)會回傳以第一個數字作為底數;第二個數字做為指數的運算結果。 它類同於 `Math.pow`,不一樣的是 `**` 可以用於 BigInt 的計算而 `Math.pow` 不行。 嘗試一下 ---- 語法 -- ```js x \*\* y ``` 簡介 -- 指數運算子是 right-associative:`a ** b ** c` 相當於 `a ** (b ** c)`。 在絕大多數的程式語言,例如 PHP、Python……等等,指數運算的優先順序比一元運算子( `+` 或 `-` )較高。但並非所有程式語言均是如此。 舉例來說,在 Bash,`**` 的優先順序就低於一元運算子。 在 Javascript,模棱兩可的求冪運算式。說得清楚一點,`+/-/~/!/delete/void/typeof` 這類一元運算子均不能置於底數之前,否則會出現 `SyntaxError`。 ```js -2 \*\* 2; // 在 Bash 的結果為 4;其他語言則為 -4 // 在 JavaScript 則是被視為語意不明。 -(2 \*\* 2); // 在 Javascript 就會得出 -4。這種寫法的語意就很明確 ``` 注意,在部分語言之中,指數運算採用插入符號 `^` ,但是在 Javascript ,`^` 則是用於XOR 位元邏輯運算子 (en-US). 範例 -- ### 指數的基本運算 ```js 2 \*\* 3; // 8 3 \*\* 2; // 9 3 \*\* 2.5; // 15.588457268119896 10 \*\* -1; // 0.1 NaN \*\* 2; // NaN ``` ### 連續使用 ```js 2 \*\* (3 \*\* 2); // 512 2 \*\* (3 \*\* 2); // 512 (2 \*\* 3) \*\* 2; // 64 ``` ### 與一元運算子一同使用 反轉指數運算結果之正負: ```js -(2 \*\* 2); // -4 ``` 計算底數為負數的指數運算: ```js (-2) \*\* 2; // 4 ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-exp-operator | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * 相加運算子 * 相減運算子 * 相除運算子 * 相乘運算子 * 餘數運算子 (en-US) * 遞增運算子 * 遞減運算子 * 負號運算子 * 正號運算子
debugger - JavaScript
debugger ======== **debugger 的宣告**會執行可用的除錯功能,例如設定斷點。如果沒有可用的除錯功能,這個宣告沒有任何作用。 語法 -- ``` debugger; ``` 示例 -- 以下示例示範了插入 debugger 宣告的程式碼,它會在函式被呼叫、而且有除錯器的時候執行除錯器。 ```js function potentiallyBuggyCode() { debugger; // 執行並驗證一些潛在的問題、或是單步執行之類的。 } ``` 呼叫除錯器時,程式會在 debugger 宣告處暫停執行。它有點像是程式碼的斷點。 ![Paused at a debugger statement.](/zh-TW/docs/Web/JavaScript/Reference/Statements/debugger/screen_shot_2014-02-07_at_9.14.35_am.png) 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-debugger-statement | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * JavaScript 除錯 * Firefox 開發工具的的除錯器
do...while 語法 - JavaScript
do...while 語法 ============= `do...while` 語法會反覆執行直到指定條件的求值結果為 false 為止。`do...while` 語法如下︰ ```js do statement while (condition); ``` `statement` 會在檢測條件之前就先執行一次。若要執行多個語句,就使用區塊語法(`{ ... }`)把語句群組化。如果 `condition` 為 true,就會再執行一次語句。每回執行以後,就會檢測條件。當條件為 false 時,就停止執行並把控制權轉移給 `do...while` 後面的語句。 範例 -- 在以下範例中,do 循環至少會反覆執行一次,並一直反覆到 i 不再小於 5 為止。 ```js do { i += 1; document.write(i); } while (i < 5); ```
var - JavaScript
var === 宣告一個變數, 同時可以非強制性地賦予一初始值。 語法 -- ``` var varname1 [= value1 [, varname2 [, varname3 ... [, varnameN]]]]; ``` `varnameN` 變數名稱。可以是任何合法的識別字符 (identifier)。 `valueN` 變數的初始值。可以是任何合法的表示式 (expression)。 說明 -- 以 `var` 宣告的變數, 其作用範圍 (scope) 及於該函數之內; 但是如果在函數外宣告, 其作用範圍則為全域性 (global) (亦即包納於全域物件之內)。 在函數之外使用以 `var` 宣告的變數是非強制的 (optional); 如果對一個未經宣告的變數賦值, 它會被暗中 (implicitly) 宣告成為一個全域變數 (亦即成為全域物件的屬性)。其中差異在於, 已宣告的變數是全域物件裡的一個無法變更 (non-configurable) 的屬性, 而未宣告的變數則是可變更的 (configurable)。 因此, 建議你一定要宣告你的變數, 不管你要將它使用於全域範圍內或者函數內。 若未宣告變數, 將非常可能導致無法預測的結果。所以, 在 ECMAScript 5 strict mode (en-US) 中, 若在函數中給一個未經宣告的函數賦值, 將會丟出錯誤。 Variable declarations, wherever they occur, are processed before any code is executed. The scope of a variable declared with `var` is its current *execution context*, which is either the enclosing function or, for variables declared outside any function, global. Assigning a value to an undeclared variable implicitly creates it as a global variable (it becomes a property of the global object) when the assignment is executed. The differences between declared and undeclared variables are: 1. Declared variables are constrained in the execution context in which they are declared. Undeclared variables are always global. ```js function x() { y = 1; // Throws a ReferenceError in strict mode var z = 2; } x(); console.log(y); // logs "1" console.log(z); // Throws a ReferenceError: z is not defined outside x ``` 2. Declared variables are created before any code is executed. Undeclared variables do not exist until the code assigning to them is executed. ```js console.log(a); // Throws a ReferenceError. console.log("still going..."); // Never executes. ``` ```js var a; console.log(a); // logs "undefined" or "" depending on browser. console.log("still going..."); // logs "still going...". ``` 3. Declared variables are a non-configurable property of their execution context (function or global). Undeclared variables are configurable (e.g. can be deleted). ```js var a = 1; b = 2; delete this.a; // Throws a TypeError in strict mode. Fails silently otherwise. delete this.b; console.log(a, b); // Throws a ReferenceError. // The 'b' property was deleted and no longer exists. ``` Because of these three differences, failure to declare variables will very likely lead to unexpected results. Thus **it is recommended to always declare variables, regardless of whether they are in a function or global scope.** And in ECMAScript 5 strict mode (en-US), assigning to an undeclared variable throws an error. ### var hoisting 在 JavaScript 中, 變數可以先使用再宣告。 因此, 建議你永遠都把變數的宣告放在函數的最頂端。否則可能導致混亂的情況。 Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code. ```js bla = 2; var bla; // ... // is implicitly understood as: var bla; bla = 2; ``` For that reason, it is recommended to always declare variables at the top of their scope (the top of global code and the top of function code) so it's clear which variables are function scoped (local) and which are resolved on the scope chain. 範例 -- ### Declaring and initializing two variables ```js var a = 0, b = 0; ``` ### Assigning two variables with single string value ```js var a = "A"; var b = a; // Equivalent to: var a, b = (a = "A"); ``` Be mindful of the order: ```js var x = y, y = "A"; console.log(x + y); // undefinedA ``` Here, `x` and `y` are declared before any code is executed, the assignments occur later. At the time "`x = y`" is evaluated, `y` exists so no `ReferenceError` is thrown and its value is '`undefined`'. So, `x` is assigned the undefined value. Then, `y` is assigned a value of 'A'. Consequently, after the first line, `x === undefined && y === 'A'`, hence the result. ### Initialization of several variables ```js var x = 0; function f() { var x = (y = 1); // x is declared locally. y is not! } f(); console.log(x, y); // Throws a ReferenceError in strict mode (y is not defined). 0, 1 otherwise. // In non-strict mode: // x is the global one as expected // y leaked outside of the function, though! ``` ### Implicit globals and outer function scope Variables that appear to be implicit globals may be references to variables in an outer function scope: ```js var x = 0; // x is declared global, then assigned a value of 0 console.log(typeof z); // undefined, since z doesn't exist yet function a() { // when a is called, var y = 2; // y is declared local to function a, then assigned a value of 2 console.log(x, y); // 0 2 function b() { // when b is called x = 3; // assigns 3 to existing global x, doesn't create a new global var y = 4; // assigns 4 to existing outer y, doesn't create a new global var z = 5; // creates a new global variable z and assigns a value of 5. } // (Throws a ReferenceError in strict mode.) b(); // calling b creates z as a global variable console.log(x, y, z); // 3 4 5 } a(); // calling a also calls b console.log(x, z); // 3 5 console.log(typeof y); // undefined as y is local to function a ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-variable-statement | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `let` * `const`
async function - JavaScript
async function ============== Baseline Widely available ------------------------- This feature is well established and works across many devices and browser versions. It’s been available across browsers since April 2017. * Learn more * See full compatibility * Report feedback **`async function`** 宣告被定義為一個回傳 `AsyncFunction` (en-US) 物件的*非同步函式* 。 你也可以使用 async function expression (en-US) 來定義一個*非同步函式*。 語法 -- ``` async function name([param[, param[, ... param]]]) { statements } ``` ### 參數 `name` 函式名稱。 `param` 傳遞至函式的參數名稱。 `statements` 組成該函式主體的陳述。 ### 回傳值 `AsyncFunction` (en-US) 物件,代表著一個非同步函式,該函式會執行該函式內的程式碼。 描述 -- 當 `async` 函式被呼叫時,它會回傳一個 `Promise`。如果該 `async` 函式回傳了一個值,`Promise` 的狀態將為一個帶有該回傳值的 resolved。如果 `async` 函式拋出例外或某個值,`Promise` 的狀態將為一個帶有被拋出值的 rejected。 async 函式內部可以使用 `await` 表達式,它會暫停此 async 函式的執行,並且等待傳遞至表達式的 Promise 的解析,解析完之後會回傳解析值,並繼續此 async 函式的執行。 **備註:** `async/await` 函式的目的在於簡化同步操作 promise 的表現,以及對多個 `Promise` 物件執行某些操作。就像 `Promise` 類似於具結構性的回呼函式,同樣地,async/await 好比將 generator 與 promise 組合起來。 範例 -- ### 簡單範例 ```js function resolveAfter2Seconds(x) { return new Promise((resolve) => { setTimeout(() => { resolve(x); }, 2000); }); } async function add1(x) { const a = await resolveAfter2Seconds(20); const b = await resolveAfter2Seconds(30); return x + a + b; } add1(10).then((v) => { console.log(v); // prints 60 after 4 seconds. }); async function add2(x) { const p_a = resolveAfter2Seconds(20); const p_b = resolveAfter2Seconds(30); return x + (await p_a) + (await p_b); } add2(10).then((v) => { console.log(v); // prints 60 after 2 seconds. }); ``` **警告:** 不要誤解 `Promise.all` 的 `await` 在 `add1` 裡,該執行為了第一個 `await` 而暫停了兩秒,接著為了第二個 `await` 又暫停了兩秒。在第一個計時器(timer)被觸發前,第二個計時器並不會被建立。而在 `add2` 裡,兩個計時器都被建立起來、也都執行 `await` 過了。這把它帶往了 resolve 所的 2 秒暫停、而不是 4 秒暫停。然而這兩個 `await` 呼叫都在連續運行,而非平行運行。`await` **並不是** `Promise.all` 的自動程式。如果你想讓兩個、甚至兩個以上的 `await` promises 同時執行(in parallel),你必須使用 `Promise.all`. ### 使用 async function 改寫 promise 鏈 一個 API 呼叫所回傳的 `Promise` 會導致一個 promise 鏈,將函式分隔成多個部份。考慮下列的程式碼: ```js function getProcessedData(url) { return downloadData(url) // returns a promise .catch((e) => { return downloadFallbackData(url); // returns a promise }) .then((v) => { return processDataInWorker(v); // returns a promise }); } ``` 它可以用一個簡單的 `async function` 來改寫成這樣: ```js async function getProcessedData(url) { let v; try { v = await downloadData(url); } catch (e) { v = await downloadFallbackData(url); } return processDataInWorker(v); } ``` 注意上方的範例,在 return 陳述中沒有使用 await 陳述,這是因為 async function 的回傳值隱含地被包裝於 `Promise.resolve` 之中。 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-async-function-definitions | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `async function expression` (en-US) * `AsyncFunction` (en-US) 物件 * `await` * "Decorating Async Javascript Functions" on "innolitics.com"
export - JavaScript
export ====== 用 **export** 可以指派函式、物件或變數,透過 `import` 宣告給外部檔案引用。 導出的模塊都會處於`嚴謹模式`,無論是否有所宣告。導出宣告無法使用嵌入式腳本(embedded script)。 語法 -- ``` export { name1, name2, …, nameN }; export { variable1 as name1, variable2 as name2, …, nameN }; // 用 var, const 也通 export let name1, name2, …, nameN; export let name1 = …, name2 = …, …, nameN; // 底下的 function 用 class, function* 也可以 export default expression; export default function (…) { … } export default function name1(…) { … } export { name1 as default, … }; export * from …; export { name1, name2, …, nameN } from …; export { import1 as name1, import2 as name2, …, nameN } from …; ``` `nameN` 外部檔案使用 `import` 時,用於辨認的名稱。 使用說明 ---- 有兩種使用 export 的方式,**named** 與 **default**。每個模組中可以有多個 named exports, 但只能有一個 default export。每種 export 都對應到一個先前說的語法。 * Named exports: ```js // 前面已經宣告的函式可以這樣輸出 export { myFunction }; // 輸出常數 export const foo = Math.sqrt(2); ``` * 預設 export (一個 js 檔案只能有一個): ```js export default function () {} // 或是 'export default class {}' // 結尾不用分號 ``` Named exports 在輸出多個值的時候很有用,在 import 的時候, 會強制根據使用相同的物件名稱. 但如果是 default export 則可以用任意的名字輸出. ``` export default k = 12; // 在test.js中這樣子寫 import m from './test' // 注意這邊因為 export default 的關係, 可以用任意名字 import 原先的k出來 console.log(m); // will log 12 ``` 以下語法並不會導出所有被引入的模塊: ``` export * from …; ``` 你必須額外引入它的預設輸出,再導出之: ``` import mod from "mod"; export default mod; ``` 使用範例 ---- ### 輸出命名過的變數 模塊內可以這樣用: ```js // module "my-module.js" function cube(x) { return x \* x \* x; } const foo = Math.PI + Math.SQRT2; var graph = { options: { color: "white", thickness: "2px", }, draw: function () { console.log("From graph draw function"); }, }; export { cube, foo, graph }; ``` 在另一個腳本就會變成這樣: ```js //You should use this script in html with the type module , //eg ''<script type="module" src="demo.js"></script>", //open the page in a httpserver,otherwise there will be a CORS policy error. //script demo.js import { cube, foo, graph } from "my-module"; graph.options = { color: "blue", thickness: "3px", }; graph.draw(); console.log(cube(3)); // 27 console.log(foo); // 4.555806215962888 ``` ### 使用預設輸出 如果我們要輸出單獨的函式、物件、class 或當做 fallback 值來輸出的話,就可以用預設輸出: ```js // module "my-module.js" export default function cube(x) { return x \* x \* x; } ``` 外部檔案的 import 用法: ```js import cube from "my-module"; console.log(cube(3)); // 27 ``` Note 注意預設輸出不能使用 var, let , const。 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-exports | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `import` * ES6 in Depth: Modules, Hacks blog post by Jason Orendorff * Axel Rauschmayer's book: "Exploring JS: Modules"
let - JavaScript
let === \*\*`let`\*\*用於宣告一個「只作用在當前區塊的變數」,初始值可選擇性的設定。 嘗試一下 ---- 語法 -- ``` let var1 [= value1] [, var2 [= value2]] [, ..., varN [= valueN]]; ``` ### 參數 `var1`, `var2`, …, `varN` 變數名稱。 `value1`, `value2`, …, `valueN` 變數的初始值,可以是任何合法的表達式。 描述 -- `let` 可以宣告只能在目前區塊、階段或表達式中作用的變數。而 `var 則是定義了一個全域變數,或是在整個 function 而不管該區塊範圍。` ### Scoping rules 宣告 `let` 的作用範圍是它們被定義的區塊,以及該區塊包含的子區塊。這樣看起來功能跟 **`var`** 很相似。主要不同的地方在於 **`var`** 作用範圍是「整個」function: ```js function varTest() { var x = 1; { var x = 2; // 這裡的 x 與 function 區塊內部的 x 是一樣的,因此會影響 function 區塊內所有的 x console.log(x); // 2 } console.log(x); // 2 } function letTest() { let x = 1; { let x = 2; // 這裡的 x 與 function 區塊內部的 x 是不同的,只會作用在這層 block 區塊中 console.log(x); // 2 } console.log(x); // 1 } ``` 在上列例子裡的最前行 `let` 和 `var` 不同,`let` 並不會在全域物件中建立變數。舉例來說: ```js var x = "global"; let y = "global"; console.log(this.x); // "global" console.log(this.y); // undefined ``` ### Emulating private members In dealing with constructors it is possible to use the **`let`** bindings to share one or more private members without using closures: ```js var Thing; { let privateScope = new WeakMap(); let counter = 0; Thing = function () { this.someProperty = "foo"; privateScope.set(this, { hidden: ++counter, }); }; Thing.prototype.showPublic = function () { return this.someProperty; }; Thing.prototype.showPrivate = function () { return privateScope.get(this).hidden; }; } console.log(typeof privateScope); // "undefined" var thing = new Thing(); console.log(thing); // Thing {someProperty: "foo"} thing.showPublic(); // "foo" thing.showPrivate(); // 1 ``` ### Temporal Dead Zone and errors with `let` Redeclaring the same variable within the same function or block scope raises a `SyntaxError` (en-US). ```js if (x) { let foo; let foo; // SyntaxError thrown. } ``` In ECMAScript 2015, **`let`** bindings are not subject to **Variable Hoisting**, which means that **`let`** declarations do not move to the top of the current execution context. Referencing the variable in the block before the initialization results in a `ReferenceError` (en-US) (contrary to a variable declared with var, which will just have the undefined value). The variable is in a "temporal dead zone" from the start of the block until the initialization is processed. ```js function do\_something() { console.log(foo); // ReferenceError let foo = 2; } ``` 你可能會在 `switch` (en-US) 中遇到錯誤,因為所有的 `case` 都屬於同樣的區塊中。 ```js switch (x) { case 0: let foo; break; case 1: let foo; // SyntaxError for redeclaration. break; } ``` ### `let` 於 `for` 迴圈的宣告範圍 You can use the `let` keyword to bind variables locally in the scope of `for` loops. This is different from the var keyword in the head of a for loop, which makes the variables visible in the whole function containing the loop. ```js var i = 0; for (let i = i; i < 10; i++) { console.log(i); } ``` However, it's important to point out that a block nested inside a case clause will create a new block scoped lexical environment, which will not produce the redeclaration errors shown above. ```js let x = 1; switch (x) { case 0: { let foo; break; } case 1: { let foo; break; } } ``` ### The temporal dead zone and `typeof` Unlike with simply undeclared variables and variables that hold a value of `undefined`, using the `typeof` operator to check for the type of a variable in that variable's TDZ will throw a `ReferenceError`: ```js // prints out 'undefined' console.log(typeof undeclaredVariable); // results in a 'ReferenceError' console.log(typeof i); let i = 10; ``` ### Another example of temporal dead zone combined with lexical scoping Due to lexical scoping, the identifier **"foo"** inside the expression `(foo + 55)` evaluates to the *if block's foo*, and **not** the *overlying variable foo* with the value of 33. In that very line, the *if block's "foo"* has already been created in the lexical environment, but has not yet reached (and **terminated**) its initialization (which is part of the statement itself): it's still in the temporal dead zone. ```js function test() { var foo = 33; { let foo = foo + 55; // ReferenceError } } test(); ``` This phenomenon may confuse you in a situation like the following. The instruction `let n of n.a` is already inside the private scope of the *for loop's block*, hence the identifier **"n.a"** is resolved to the property 'a' of the *'n' object located in the first part of the instruction itself* ("let n"), which is still in the temporal dead zone since its declaration statement has not been reached and **terminated**. ```js function go(n) { // n here is defined! console.log(n); // Object {a: [1,2,3]} for (let n of n.a) { // ReferenceError console.log(n); } } go({ a: [1, 2, 3] }); ``` Other situations ---------------- When used inside a block, **`let`** limits the variable's scope to that block. Note the difference between **`var`** whose scope is inside the function where it is declared. ```js var a = 1; var b = 2; if (a === 1) { var a = 11; // the scope is global let b = 22; // the scope is inside the if-block console.log(a); // 11 console.log(b); // 22 } console.log(a); // 11 console.log(b); // 2 ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-let-and-const-declarations | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `var` * `const` * ES6 In Depth: `let` and `const` * Breaking changes in `let` and `const` in Firefox 44.
for...in - JavaScript
for...in ======== 迭代物件的可列舉屬性。對每個相異屬性,執行陳述式。 | Statement | | --- | | Implemented in: | JavaScript 1.0 | | ECMA Version: | ECMA-262 | 語法 -- ``` for (變數 in 物件) {... } ``` ### 參數 `變數` A different property name is assigned to *variable* on each iteration. `物件` Object whose enumerable properties are iterated. Description ----------- `for...in` 迴圈只迭代可列舉屬性。由內建建構式(如:Array、Object) 製造的物件,從 `Object.prototype` 和 `String.prototype` 繼承了不可列舉屬性,如: `String` (en-US)的`indexOf` (en-US) 方法,或 `Object` (en-US)的 `toString` (en-US) 方法。 迴圈將迭代全部可列舉屬性,包括了物件自身的和物件繼承自它的建構式之原型的可列舉屬性。(原型鏈上較接近物件的屬性覆蓋原型的屬性) A `for...in` loop iterates over the properties of an object in an arbitrary order (see the delete operator (en-US) for more on why one cannot depend on the seeming orderliness of iteration, at least in a cross-browser setting). If a property is modified in one iteration and then visited at a later time, its value in the loop is its value at that later time. A property that is deleted before it has been visited will not be visited later. Properties added to the object over which iteration is occurring may either be visited or omitted from iteration. In general it is best not to add, modify or remove properties from the object during iteration, other than the property currently being visited. There is no guarantee whether or not an added property will be visited, whether a modified property (other than the current one) will be visited before or after it is modified, or whether a deleted property will be visited before it is deleted. **備註:** If you only want to consider properties attached to the object itself, and not its prototypes, use getOwnPropertyNames (en-US) or perform a hasOwnProperty (en-US) check (propertyIsEnumerable (en-US) can also be used). Alternatively, if you know there won't be any outside code interference, you can extend built-in prototypes with a check method. **備註:** `for..in` 不應該用來迭代一個索引順序很重要的陣列 (en-US)。 陣列索引只是以整數命名的可列舉屬性,其他方面等同於一般物件屬性。 無法擔保 `for...in` 以特定順序傳回索引,並且它將傳回全部可列舉屬性,包括非整數名的,以及繼承而來的可列舉屬性。因為迭代的順序依賴於 JavaScript 引擎的實作,在不同引擎下,迭代一個陣列可能不是以一個一致的順序存取陣列元素。因此,當你迭代陣列,且該陣列的存取順序很重要時,最好是使用以數值索引的 for (en-US) 迴圈 (或 Array.forEach (en-US) 或非標準 `for...of` (en-US) 迴圈)。 Examples -------- The following function takes as its arguments an object and the object's name. It then iterates over all the object's enumerable properties and returns a string of the property names and their values. ```js var o = { a: 1, b: 2, c: 3 }; function show\_props(obj, objName) { var result = ""; for (var prop in obj) { result += objName + "." + prop + " = " + obj[prop] + "\n"; } return result; } alert( show\_props(o, "o"), ); /\* alerts (in different lines): o.a = 1 o.b = 2 o.c = 3 \*/ ``` The following function illustrates the use of hasOwnProperty: the inherited properties are not displayed. ```js var triangle = { a: 1, b: 2, c: 3 }; function ColoredTriangle() { this.color = "red"; } ColoredTriangle.prototype = triangle; function show\_own\_props(obj, objName) { var result = ""; for (var prop in obj) { if (obj.hasOwnProperty(prop)) { result += objName + "." + prop + " = " + obj[prop] + "\n"; } } return result; } o = new ColoredTriangle(); alert(show\_own\_props(o, "o")); /\* alerts: o.color = red \*/ ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-for-in-and-for-of-statements | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. See also -------- * `for...of` (en-US) - a similar statement that iterates over the property *values* * `for each...in` - a similar statement, but iterates over the values of object's properties, rather than the property names themselves (New in JavaScript 1.6 but deprecated) * for (en-US) * Generator expressions (en-US) (uses the `for...in` syntax) * Enumerability and ownership of properties (en-US) * `getOwnPropertyNames` (en-US) * `hasOwnProperty` (en-US) * `Array.prototype.forEach` (en-US)
const - JavaScript
const ===== Constants (常數) 有點像使用 `let` 所宣告的變數,具有區塊可視範圍。常數不能重複指定值,也不能重複宣告。嘗試一下 ---- 語法 -- ``` const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]]; ``` `nameN` 常數的名稱,可以是任何合法的 identifier。 `valueN` 常數的值,可以是任何合法的 expression,包括 function expression。 描述 -- 上述宣告建立一個常數,它的可視範圍可能是全域的,或是在它所宣告的區域區塊中。 和 `var` 變數不同的是,全域的常數不會變成 window 物件的屬性。常數必須要初始化;也就是說,你必須在宣告常數的同一個敘述式中指定這個常數的值。(這很合理,因為稍後就不能再變更常數的值了) 宣告 **`const`** 會對於它的值建立一個唯讀的參考。並不是說這個值不可變更,而是這個變數不能再一次指定值。例如,假設常數的內容(值)是個物件,那麼此物件的內容(物件的參數)是可以更改的。 所有關於 "temporal dead zone" 的狀況,都適用於 `let` and `const` 。 在相同的可視範圍內,常數不能和函數,變數具有相同名稱。 範例 -- 以下範例展示常數的行為。請在你的瀏覽器中試試以下程式碼。 ```js // 注意: 常數可以宣告成大寫或小寫, // 但習慣上使用全部大寫的字母。 // 定義一個常數 MY\_FAV 並賦予它的值為7 const MY\_FAV = 7; // 這裡會發生錯誤 - Uncaught TypeError: Assignment to constant variable. MY\_FAV = 20; // MY\_FAV 是 7 console.log('我喜歡的數字是: ' + MY\_FAV); // 嘗試重複宣告同名的常數,將會發生錯誤 - Uncaught SyntaxError: Identifier 'MY\_FAV' has already been declared const MY\_FAV = 20; // MY\_FAV 這個名稱已經保留給上面的常數, 所以這裡也會錯誤。 var MY\_FAV = 20; // 這式子也會錯誤 let MY\_FAV = 20; // 很重要,請注意區塊可視範圍的特性。 if (MY\_FAV === 7) { // 以下式子沒有問題,並且會建立一個名叫 MY\_FAV 的具有區塊可視範圍的變數。 // (等同於使用 let 來宣告一個具有區塊可視範圍的非常數變數。) let MY\_FAV = 20; // MY\_FAV 現在變成 20 console.log('我喜歡的數字是:' + MY\_FAV); // 這會將變數懸掛於全域,而導致錯誤。(與常數同名) var MY\_FAV = 20; } // MY\_FAV 仍然是 7 console.log('我喜歡的數字是:' + MY\_FAV); // 發生錯誤 - Uncaught SyntaxError: Missing initializer in const declaration const FOO; // 常數的值可以是一個物件 const MY\_OBJECT = {'key': 'value'}; // 嘗試覆寫該物件將會發生錯誤 - Uncaught TypeError: Assignment to constant variable. MY\_OBJECT = {'OTHER\_KEY': 'value'}; // 然而, 物件的屬性並沒有被保護, // 所以,以下敘述式沒有問題。 MY\_OBJECT.key = 'otherValue'; // Use Object.freeze() to make object immutable // 對陣列來說也是一樣 const MY\_ARRAY = []; // 可以把項目加到陣列中。 MY\_ARRAY.push('A'); // ["A"] // 然而,對這個變數指定新陣列,將會發生錯誤 - Uncaught TypeError: Assignment to constant variable. MY\_ARRAY = ['B']; ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-let-and-const-declarations | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參閱 -- * `var` * `let` * Constants in the JavaScript Guide
switch - JavaScript
switch ====== **`switch` 語句**會比對一個表達式裡頭的值是否符合 `case` 條件,然後執行跟這個條件相關的陳述式 (en-US),以及此一符合條件以外,剩下其他條件裡的陳述式。 嘗試一下 ---- 語法 -- ```js switch (expression) { case value1: //當 expression 的值符合 value1 //要執行的陳述句 [break;] case value2: //當 expression 的值符合 value2 //要執行的陳述句 [break;] ... case valueN: //當 expression 的值符合 valueN //要執行的陳述句 [break;] [default: //當 expression 的值都不符合上述條件 //要執行的陳述句 [break;]] } ``` `expression` 一個表達式其結果用來跟每個 `case` 條件比對。 `case valueN` 選擇性 一個 `case` 條件是用來跟 `expression` 匹配的。 如果 `expression` 符合特定的 `valueN`,那在 case 條件裡的語句就會執行,直到這個 `switch` 陳述式結束或遇到一個 `break` 。 `default` 選擇性 一個 `default` 條件;倘若有這個條件,那在 `expression` 的值並不符合任何一個 `case` 條件的情況下,就會執行這個條件裡的語句。 描述 -- 一個 switch 陳述式會先評估自己的 expression。然後他會按照 `case` 條件順序開始尋找,直到比對到第一個表達式值跟輸入 expression 的值相等的 case 條件(使用嚴格的邏輯運算子 (en-US), `===`)並把控制流交給該子句、並執行裡面的陳述式(如果給定值符合多個 case,就執行第一個符合的 case,就算該 case 與其他 case 不同) If no matching `case` clause is found, the program looks for the optional `default` clause, and if found, transfers control to that clause, executing the associated statements. If no `default` clause is found, the program continues execution at the statement following the end of `switch`. 按照慣例, `default` 語句會是最後一個條件,但不一定要存在。 The optional `break` statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If `break` is omitted, the program continues execution at the next statement in the `switch` statement. 範例 -- ### 使用 `switch` In the following example, if `expr` evaluates to "Bananas", the program matches the value with case "Bananas" and executes the associated statement. When `break` is encountered, the program breaks out of `switch` and executes the statement following `switch`. If `break` were omitted, the statement for case "Cherries" would also be executed. ```js switch (expr) { case "Oranges": console.log("Oranges are $0.59 a pound."); break; case "Apples": console.log("Apples are $0.32 a pound."); break; case "Bananas": console.log("Bananas are $0.48 a pound."); break; case "Cherries": console.log("Cherries are $3.00 a pound."); break; case "Mangoes": case "Papayas": console.log("Mangoes and papayas are $2.79 a pound."); break; default: console.log("Sorry, we are out of " + expr + "."); } console.log("Is there anything else you'd like?"); ``` ### 如果我忘記 break 會發生什麼事? If you forget a break then the script will run from the case where the criterion is met and will run the case after that regardless if criterion was met. See example here: ```js var foo = 0; switch (foo) { case -1: console.log("negative 1"); break; case 0: // foo is 0 so criteria met here so this block will run console.log(0); // NOTE: the forgotten break would have been here case 1: // no break statement in 'case 0:' so this case will run as well console.log(1); break; // it encounters this break so will not continue into 'case 2:' case 2: console.log(2); break; default: console.log("default"); } ``` ### 我可以在 cases 中間放 default 嗎? Yes, you can! JavaScript will drop you back to the default if it can't find a match: ```js var foo = 5; switch (foo) { case 2: console.log(2); break; // it encounters this break so will not continue into 'default:' default: console.log("default"); // fall-through case 1: console.log("1"); } ``` It also works when you put default before all other cases. ### 同時使用多個條件 case 的方法 Source for this technique is here: Switch statement multiple cases in JavaScript (Stack Overflow) #### Multi-case - single operation This method takes advantage of the fact that if there is no break below a case statement it will continue to execute the next case statement regardless if the case meets the criteria. See the section titled "What happens if I forgot a break?" This is an example of a single operation sequential switch statement, where four different values perform exactly the same. ```js var Animal = "Giraffe"; switch (Animal) { case "Cow": case "Giraffe": case "Dog": case "Pig": console.log("This animal will go on Noah's Ark."); break; case "Dinosaur": default: console.log("This animal will not."); } ``` #### Multi-case - chained operations This is an example of a multiple-operation sequential switch statement, where, depending on the provided integer, you can receive different output. This shows you that it will traverse in the order that you put the case statements, and it does not have to be numerically sequential. In JavaScript, you can even mix in definitions of strings into these case statements as well. ```js var foo = 1; var output = "Output: "; switch (foo) { case 0: output += "So "; case 1: output += "What "; output += "Is "; case 2: output += "Your "; case 3: output += "Name"; case 4: output += "?"; console.log(output); break; case 5: output += "!"; console.log(output); break; default: console.log("Please pick a number from 0 to 5!"); } ``` The output from this example: | Value | Log text | | --- | --- | | foo is NaN or not 1, 2, 3, 4, 5 or 0 | Please pick a number from 0 to 5! | | 0 | Output: So What Is Your Name? | | 1 | Output: What Is Your Name? | | 2 | Output: Your Name? | | 3 | Output: Name? | | 4 | Output: ? | | 5 | Output: ! | ### Block-scope variables within `switch` statements With ECMAScript 2015 (ES6) support made available in most modern browsers, there will be cases where you would want to use let and const statements to declare block-scoped variables. Take a look at this example: ```js const action = "say\_hello"; switch (action) { case "say\_hello": let message = "hello"; console.log(message); break; case "say\_hi": let message = "hi"; console.log(message); break; default: console.log("Empty action received."); break; } ``` This example will output the error `Uncaught SyntaxError: Identifier 'message' has already been declared` which you were not probably expecting. This is because the first `let message = 'hello';` conflicts with second let statement `let message = 'hi';` even they're within their own separate case statements `case 'say_hello':` and `case 'say_hi':`; ultimately this is due to both `let` statements being interpreted as duplicate declarations of the same variable name within the same block scope. We can easily fix this by wrapping our case statements with brackets: ```js const action = "say\_hello"; switch (action) { case "say\_hello": { // added brackets let message = "hello"; console.log(message); break; } // added brackets case "say\_hi": { // added brackets let message = "hi"; console.log(message); break; } // added brackets default: { // added brackets console.log("Empty action received."); break; } // added brackets } ``` This code will now output `hello` in the console as it should, without any errors at all. 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-switch-statement | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 你也可以看看 ------ * `if...else`
continue 語法 - JavaScript
continue 語法 =========== `continue` 語法可用來重新開始 `while`、`do-while`、`for`、`label` 語法。 * 當你使用沒加標籤的 `continue` 時,他會終止這一次的最內層的 `while`、`do-while`、`for` 語法的反覆過程,並繼續執行下一次的反覆過程。與 `break` 語法相較之下,`continue` 不會終止整個循環的執行。在 `while` 循環中,他會跳回條件處。在 `for` 循環中,他會跳回遞增表達式。 * 當你使用加上標籤的 `continue` 時,他會跳到以 `label` 標記的循環語句。 `continue` 語法如下︰ 1. `continue` 2. `continue label` 範例 1 ---- 以下範例示範加上 `continue` 語法的 `while` 循環,`continue` 語法會在 `i` 值為 3 時執行。因此,`n` 的值依序為 1、3、7、12。 ```js i = 0; n = 0; while (i < 5) { i++; if (i == 3) continue; n += i; } ``` 範例 2 ---- 已加上標籤的語法 `checkiandj` 內含已加上標籤的語法 `checkj`。如果遇到 `continue`,程式會終止 `checkj` 這一次的反覆過程,並開始下一次的反覆過程。每當遇到 `continue`,就會反覆執行 `checkj` 直到他的條件返回 false 為止。當返回 false 時,`checkiandj` 語句完成了餘數的計算,且 `checkiandj` 會反覆執行,直到他的條件返回為 false 為止。當返回 false 時,程式繼續執行 `checkiandj` 後面的語句。 如果 `continue` 有一個 `checkiandj` 標籤,程式就會從 `checkiandj` 語句的開始處繼續執行。 ```js checkiandj: while (i < 4) { document.write(i + "<br/>"); i += 1; checkj: while (j > 4) { document.write(j + "<br/>"); j -= 1; if (j % 2 == 0) continue checkj; document.write(j + " is odd.<br/>"); } document.write("i = " + i + "<br/>"); document.write("j = " + j + "<br/>"); } ```
try...catch 語法 - JavaScript
try...catch 語法 ============== `try...catch` 語法標記出一整塊需要測試的語句,並指定一個以上的回應方法,萬一有例外拋出時,`try...catch` 語句就會捕捉。 `try...catch` 語法由 `try` 區塊所組成,其中內含一個以上的語句,和零個以上的 `catch` 區塊,其中內含語句用來指明當例外在 try 區塊裡拋出時要做些什麼。也就是當你希望 `try` 區塊成功,但如果他不成功時,你會想要把控制權移交給 `catch` 區塊。如果任何在 `try` 區塊內部裡的語句(或者在 `try` 區塊內部呼叫的函數裡)拋出例外,控制權將立即轉移給 `catch` 區塊。如果沒有例外從 `try` 區塊裡拋出,就會跳過 `catch` 區塊。`finally` 區塊會在 `try` 或 `catch` 區塊執行之後才執行,但會在 `try...catch` 語法後面的語句之前執行。 以下範例使用 `try...catch` 語法。本範例呼叫函數,這個函數是用來在陣列裡根據傳給函數的值來查詢月份的名稱。如果傳入的值不符合月份的數字 (1-12),就會拋出值為 `InvalidMonthNo` 的例外,而且在 `catch` 區塊裡的語句會把 `monthName` 變數設定為 `unknown`。 ```js function getMonthName(mo) { mo = mo - 1; // 針對陣列索引調整月份的數字 (1=Jan, 12=Dec) var months = new Array( "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", ); if (months[mo] != null) { return months[mo]; } else { throw "InvalidMonthNo"; } } try { // 需要測試的語句 monthName = getMonthName(myMonth); // 可拋出例外的函數 } catch (e) { monthName = "unknown"; logMyErrors(e); // 把例外物件傳給錯誤處理器 } ``` #### catch 區塊 你可以使用單一的 `catch` 區塊來處理所有在 `try` 區塊裡可能會產生的例外,或者你也可以使用分離的 `catch` 區塊,每一個皆各自處理特定的例外類型。 **單一 catch 區塊** 使用單一 `try...catch` 語法的 `catch` 區塊針對在 `try` 區塊裡拋出的所有例外來執行錯誤處理的代碼。 單一的 `catch` 區塊語句如下︰ ```js catch (catchID) { statements } ``` `catch` 區塊所指定的識別子(前面語句裡的 `catchID`)持有由 `throw` 語法所指定的值。你可以使用這個識別子來取得有關於被拋出的例外的資訊。當進入 `catch` 區塊時,JavaScript 就會建立這個識別子。識別子只能在 `catch` 區塊的期間內持續作用。`catch` 區塊執行結束以後,識別子就不再能使用。 舉例來說,以下代碼會拋出例外。當例外出現的時候,控制權就轉移給 `catch` 區塊。 ```js try { throw "myException"; // 產生例外 } catch (e) { // 用來處理任何例外的語句 logMyErrors(e); // 把例外物件傳給錯誤處理器 } ``` **多重 catch 區塊** 單一的 `try` 語句可以對應複數個有前提條件的 `catch` 區塊,每一個皆可處理特定的例外的類型。於是,當指定的的例外被拋出時,就只會進入適當條件的 `catch` 區塊。你也可以針對所有未指定的例外,使用選用性的對應所有例外的 `catch` 區塊來作為語法裡最後一個的 catch 區塊。 舉例來說,以下函數呼叫三個其他的函數(已在別處定義了)來檢驗自己的參數。如果檢驗函數判斷出他所要檢驗的元素是無效的話,他就返回 0,導致呼叫者拋出對應的例外。 ```js function getCustInfo(name, id, email) { var n, i, e; if (!validate\_name(name)) throw "InvalidNameException"; else n = name; if (!validate\_id(id)) throw "InvalidIdException"; else i = id; if (!validate\_email(email)) throw "InvalidEmailException"; else e = email; cust = n + " " + i + " " + e; return cust; } ``` 有各種條件的 `catch` 區塊會把控制權安排給適當的例外處理器。 ```js try { // 可以拋出三個例外的函數 getCustInfo("Lee", 1234, "[email protected]") } catch (e if e == "InvalidNameException") { // 針對無效的名稱呼叫處理器 bad\_name\_handler(e) } catch (e if e == "InvalidIdException") { // 針對無效的 ID 呼叫處理器 bad\_id\_handler(e) } catch (e if e == "InvalidEmailException") { // 針對無效的電子郵件位址呼叫處理器 bad\_email\_handler(e) } catch (e){ // 不知道該做什麼,就記在日誌裡 logError(e) } ``` #### finally 區塊 `finally` 區塊內含的語句,會在 try 和 catch 區塊執行以後、並在 `try...catch` 語法後面的語句之前來執行。無論有沒有被拋出的例外,`finally` 區塊都會執行。如果有被拋出的例外,即使沒有 catch 區塊來處理這些例外,還是會執行 `finally` 區塊裡的語句。 當出現例外時,你可以使用 `finally` 區塊來使你的 Script 優美的停止。舉例來說,你可能需要釋放 Script 所佔用的資源。以下範例開啟了檔案,並執行使用這個檔案(伺服端的 JavaScript 可讓你存取檔案)的語句。如果在開啟檔案時有例外被拋出,`finally` 區塊會在 Script 停止之前把檔案關閉。 ```js openMyFile(); try { writeMyFile(theData); // 這裡有可能拋出錯誤 } catch (e) { handleError(e); // 如果我們得到錯誤,就處理他 } finally { closeMyFile(); // 永遠會關閉這項資源 } ``` #### try...catch 語法的嵌套 你可以嵌套一個以上的 `try...catch` 語法。如果有一個內部的 `try...catch` 語法沒有 catch 區塊,圍住這些 `try...catch` 語法的 catch 區塊就會被用來比對。 #### Error 物件的用處 根據錯誤的類型,你有可能使用 「name」 和 「message」 屬性來取得更多明確的訊息。「name」 提供錯誤的一般類別(例如,「DOMException」 或 「Error」),「message」 通常提供更為簡練的訊息,如此就能把錯誤物件轉換為字串來取得訊息。 如果你要拋出你自己的例外,以從這些屬性取得好處(例如,如果你的 catch 區塊不區分你自己的例外和系統的例外的話),你可以使用錯誤建構子。例如︰ ```js function doSomethingErrorProne () { if (ourCodeMakesAMistake()) { throw (new Error('The message')); } else { doSomethingToGetAJavascriptError(); } } .... try { doSomethingErrorProne(); } catch (e) { alert(e.name);// 警報 'Error' alert(e.message); // 警報 'The message' 或 JavaScript 錯誤訊息 } ``` * « 前頁 * 次頁 »
return - JavaScript
return ====== **`return` 表達式**會終止函式執行,並指明函式呼叫器(function caller)要回傳的數值。 嘗試一下 ---- 語法 -- ``` return [[expression]]; ``` `expression` 要被回傳的表達式。如果省略了表達式,函式就會回傳 `undefined`。 敘述 -- 如果在 function body 內宣告 `return` 的話,函式執行就會終止。如果指定數值的話,函式呼叫器就會回傳給定的數值。例如說,以下函式會回傳 `x` 參數的次方數。 ```js function square(x) { return x \* x; } var demo = square(3); // demo will equal 9 ``` 如果省略了表達式,函式就會回傳 `undefined`。 以下所有的 return 宣告都會終止函式執行: ```js return; return true; return false; return x; return x + y / 3; ``` ### 自動插入分號 `return` 宣告會受自動插入分號(automatic semicolon insertion,ASI)影響。No line terminator is allowed between the `return` keyword and the expression. ```js return; a + b; ``` 會因為 ASI 而變成: ```js return; a + b; ``` 主控台會警告「unreachable code after return statement」(在 return 宣告後面有無法抵達的程式碼)。 **備註:** 從 Gecko 40 開始,如果主控台發現在 return 宣告後面有無法抵達的程式碼,就會顯示警告。 要避免 ASI 問題,可以添加括號: ```js return a + b; ``` 示例 -- ### 終止函式 在到達呼叫 `return` 的地方後,函式會立即停止。 ```js function counter() { for (var count = 1; ; count++) { // 無限迴圈 console.log(count + "A"); // 直到 5 if (count === 5) { return; } console.log(count + "B"); // 直到 4 } console.log(count + "C"); // 永不顯示 } counter(); // 輸出: // 1A // 1B // 2A // 2B // 3A // 3B // 4A // 4B // 5A ``` ### 函式回傳 請參見閉包。 ```js function magic(x) { return function calc(x) { return x \* 42; }; } var answer = magic(); answer(1337); // 56154 ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-return-statement | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * 函式 (en-US) * 閉包
label - JavaScript
label ===== **標記陳述式**可以和 `break` 或 `continue` 語句一起使用。標記就是在一條陳述式前面加個可以引用的識別符號。 嘗試一下 ---- **備註:** 標記的迴圈或程式碼區塊非常罕見。通常可以使用函式呼叫而不是使用迴圈跳轉。 語法 -- ``` label : statement ``` `label` 任何不是保留字的 JavaScript 識別符號。 `statement` 一個 JavaScript 陳述式。`break` 可用於任何標記陳述式,而 `continue` 可用於循環標記陳述式。 描述 -- 可使用一個標籤來唯一標記一個循環,然後使用 `break` 或 `continue` 陳述式來指示程式是否中斷循環或繼續執行。 需要注意的是 JavaScript **沒有** `goto` 陳述式,標記只能和 `break` 或 `continue` 一起使用。 在嚴格模式中,你不能使用 「`let`」 作為標籤名稱。它會拋出一個`SyntaxError` (en-US)(let 是一個保留的識別符號)。 範例 -- ### 在 `for` 迴圈中使用帶標記的 `continue` ```js var i, j; loop1: for (i = 0; i < 3; i++) { //The first for statement is labeled "loop1" loop2: for (j = 0; j < 3; j++) { //The second for statement is labeled "loop2" if (i === 1 && j === 1) { continue loop1; } console.log("i = " + i + ", j = " + j); } } // Output is: // "i = 0, j = 0" // "i = 0, j = 1" // "i = 0, j = 2" // "i = 1, j = 0" // "i = 2, j = 0" // "i = 2, j = 1" // "i = 2, j = 2" // Notice how it skips both "i = 1, j = 1" and "i = 1, j = 2" ``` ### 使用帶標記的 `continue` 陳述式 給定一組資料和一組測試,下面的例子可以統計通過測試的資料。 ```js var itemsPassed = 0; var i, j; top: for (i = 0; i < items.length; i++) { for (j = 0; j < tests.length; j++) { if (!tests[j].pass(items[i])) { continue top; } } itemsPassed++; } ``` ### 在 `for` 迴圈中使用帶標記的 `break` ```js var i, j; loop1: for (i = 0; i < 3; i++) { //The first for statement is labeled "loop1" loop2: for (j = 0; j < 3; j++) { //The second for statement is labeled "loop2" if (i === 1 && j === 1) { break loop1; } console.log("i = " + i + ", j = " + j); } } // Output is: // "i = 0, j = 0" // "i = 0, j = 1" // "i = 0, j = 2" // "i = 1, j = 0" // Notice the difference with the previous continue example ``` ### 使用帶標記 `break` 陳述式 給定一組資料和一組測試,下面的例子判斷是否所有的資料均通過了測試。 ```js var allPass = true; var i, j; top: for (i = 0; items.length; i++) for (j = 0; j < tests.length; i++) if (!tests[j].pass(items[i])) { allPass = false; break top; } ``` ### 在標記的區塊中使用 `break` 你可以在程式碼區塊中使用標記,但只有 `break` 陳述式可以使用非迴圈的標記。 ```js foo: { console.log("face"); break foo; console.log("this will not be executed"); } console.log("swap"); // this will log: // "face" // "swap ``` ### 標記的函式宣告式 從 ECMAScript 2015 開始,標準的函式宣告式現在對規範的 Web 相容性附件中的非嚴格程式碼進行了標準化。 ```js L: function F() {} ``` 在嚴格模式中,這會拋出 `SyntaxError` (en-US) 例外: ```js "use strict"; L: function F() {} // SyntaxError: functions cannot be labelled ``` 產生器函式既不能在嚴格模式中標記,也不能在非嚴格模式中標記: ```js L: function\* F() {} // SyntaxError: generator functions cannot be labelled ``` 規格 -- | Specification | | --- | | ECMAScript Language Specification # sec-labelled-statements | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 相關連結 ---- * `break` * `continue`
if...else - JavaScript
if...else ========= 當條件成立的時候會執行 if 陳述式裡的程式,而不成立時則執行另外一個陳述式。 嘗試一下 ---- 語法 -- ```js if (condition) statement1 // With an else clause if (condition) statement1 else statement2 ``` `condition` 一個成立或不成立的運算式。 `statement1` 如果 if 中的條件(conditions)為真時執行陳述式(statements)。陳述式可以為任何內容,包含巢狀式(nested)的 if 陳述。當要執行多行的陳述式(statements)時,使用區塊(block)將所要執行的陳述式包覆。如果不需要執行任何動作時,則不撰寫任何陳述式(empty statement)。 `statement2` 當件不成立時所執行的部份,當 else 被撰寫時才會被執行。可以是任何的陳述式,包含使用區塊(block)及巢狀(nested)的陳述。 描述 -- 多重的 `if...else` 陳述式可以使用 `else if` 子句來建立一個巢狀結構的句子。要記住,在 JavaScript 中沒有 `elseif` (一個單字) 的語法可以用。 ```js if (condition1) statement1 else if (condition2) statement2 else if (condition3) statement3 // … else statementN ``` 將巢狀結構適當的排版後,我們能更了解其背後運作的邏輯: ```js if (condition1) statement1 else if (condition2) statement2 else if (condition3) statement3 // … ``` 如果在一個條件式中有多個陳述要執行,可以使用區塊陳述式(`{ ... }`) 把所有陳述包在一起。 通常來說,無論如何都使用區塊陳述式是個很好的習慣,尤其是當你使用巢狀結構的 `if` 陳述式時,這會讓人更容易理解你的程式碼。 ```js if (condition) { statements1 } else { statements2 } ``` 不要被Boolean物件中,布林值的 `true` 和 `false` 給混淆了。任何值只要不是 `false`、 `undefined`、 `null`、 `0`、 `NaN`,或者空字串 (`""`),並且任何物件,包括其值是 `false`的布林物件 ,仍然會被條件陳述式視為條件成立。舉例而言: ```js var b = new Boolean(false); if (b) // this condition is truthy ``` 實例 -- ### 使用 `if...else` ```js if (cipherChar === fromChar) { result += toChar; x++; } else { result += clearChar; } ``` ### 使用 `else if` 要記得 JavaScript 沒有 `elseif` 可以使用。不過,你可以使用 `else` 和 `if`中間夾著空白的語法: ```js if (x > 50) { /\* do something \*/ } else if (x > 5) { /\* do something \*/ } else { /\* do something \*/ } ``` ### 條件表達式中的賦值 建議不要在條件表達式中直接對物件賦值,因為這會使人在瀏覽程式碼時很容易將賦值( assignment )與相等( equality )混淆。舉例而言,不要使用以下寫法: ```js if ((x = y)) { /\* do the right thing \*/ } ``` 如果你必須在條件表達式中使用賦值,最好 ˇ 的作法是以額外的括號包住賦值語句,如下所示: ```js if (x = y) { // do something } ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-if-statement | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `block` * `switch` * `conditional operator`
for 語法 - JavaScript
for 語法 ====== `for` 循環反覆執行直到指定的條件的求值為 false 為止。JavaScript 的 for 循環和 Java 和 C 的 for 循環很類似。`for` 語法如下︰ ```js for ([initialExpression]; [condition]; [incrementExpression]) statement; ``` 執行 `for` 循環時,會執行以下步驟︰ 1. 執行初始化表達式 `initialExpression`。這個表達式通常會初始化為 1 以上的計數器,不過也可以是任意複雜程度的表達式。也可以在表達式裡宣告變數。 2. 對 `condition` 表達式求值。如果 `condition` 的值為 true,就會執行循環語法。如果 `condition` 的值為 false,就終止 `for` 循環。如果完全省略 `condition` 表達式,條件就會被代入為 true。 3. 執行 `statement`。若要執行多個語句,就使用區塊語法(`{ ... }`)把這些語句群組化。 4. 執行更新表達式 `incrementExpression`,並回到第 2 步驟。 範例 -- 以下函數內含 `for` 語法,計數至下拉式選單的已選擇選項的數目為止(Select 物件允許複選)。`for` 語法宣告變數 `i` 並以 0 初始化。他會檢驗 `i` 是否小於 `Select` 物件的選項數目,持續執行 `if` 語句,並在每一次循環之後以 1 遞增 `i`。 ```html <script type="text/javascript"> //<![CDATA[ function howMany(selectObject) { var numberSelected = 0; for (var i = 0; i < selectObject.options.length; i++) { if (selectObject.options[i].selected) numberSelected++; } return numberSelected; } //]]> </script> <form name="selectForm"> <p> <strong>Choose some music types, then click the button below:</strong> <br /> <select name="musicTypes" multiple="multiple"> <option selected="selected">R&B</option> <option>Jazz</option> <option>Blues</option> <option>New Age</option> <option>Classical</option> <option>Opera</option> </select> </p> <p> <input type="button" value="How many are selected?" onclick="alert ('Number of options selected: ' + howMany(document.selectForm.musicTypes))" /> </p> </form> ``` * « 前頁 * 次頁 »
function* - JavaScript
function\* ========== **`function*`** 宣告式(`function` 關鍵字後面跟著一個星號)定義了一個*生成器函式(generator function)*,他會回傳一個`生成器(Generator)` (en-US)物件。 嘗試一下 ---- 你可以透過 `GeneratorFunction` (en-US) 建構式來定義生成器函式。 語法 -- ``` function* name([param[, param[, ... param]]]) { statements } ``` `name` 函式名稱。 `param` 要被傳入函式的引數名稱,一個函式最多可以擁有 255 個引數。 `statements` statements 構成了函式內容的陳述式。 描述 -- 生成器是可以離開後再次進入的函式。在兩次進入之間,生成器的執行狀態(變數綁定狀態)會被儲存。 呼叫生成器函式並不會讓裡面的程式碼立即執行,而是會回傳一個針對該函式的迭代器(iterator)物件。當呼叫迭代器的 `next()` 方法時,生成器函式將會執行到遭遇的第一個 `yield` (en-US) 運算式,該運算式給定的值將從迭代器中回傳,如果是 `yield*` (en-US) 則會交給另一個生成器函式處理。`next()` 方法回傳一個物件,該物件有 `value` 屬性,包含了產生的數值,還有 `done` 屬性,為布林值,指出該生成器是否產出最後的數值。呼叫 `next()` 方法如果帶有一個參數,將會讓先前暫停的生成器函式恢復執行,以該參數值取代先前暫停的 `yield` 陳述式。 生成器中的 `return` 陳述式被執行時,會讓生成器 `done` 狀態為真。若有數值被返回的動作帶回,將是放在 `value` 傳回的。已返回的生成器不會再產生任何數值。 範例 -- ### 簡單例子 ```js function\* idMaker() { var index = 0; while (index < index + 1) yield index++; } var gen = idMaker(); console.log(gen.next().value); // 0 console.log(gen.next().value); // 1 console.log(gen.next().value); // 2 console.log(gen.next().value); // 3 // ... ``` ### yield\* 的範例 ```js function\* anotherGenerator(i) { yield i + 1; yield i + 2; yield i + 3; } function\* generator(i) { yield i; yield\* anotherGenerator(i); yield i + 10; } var gen = generator(10); console.log(gen.next().value); // 10 console.log(gen.next().value); // 11 console.log(gen.next().value); // 12 console.log(gen.next().value); // 13 console.log(gen.next().value); // 20 ``` ### 傳入引數至生成器 ```js function\* logGenerator() { console.log(0); console.log(1, yield); console.log(2, yield); console.log(3, yield); } var gen = logGenerator(); // the first call of next executes from the start of the function // until the first yield statement gen.next(); // 0 gen.next("pretzel"); // 1 pretzel gen.next("california"); // 2 california gen.next("mayonnaise"); // 3 mayonnaise ``` ### 生成器中的回傳陳述式 ```js function\* yieldAndReturn() { yield "Y"; return "R"; yield "unreachable"; } var gen = yieldAndReturn(); console.log(gen.next()); // { value: "Y", done: false } console.log(gen.next()); // { value: "R", done: true } console.log(gen.next()); // { value: undefined, done: true } ``` ### 生成器無法被建構 ```js function\* f() {} var obj = new f(); // throws "TypeError: f is not a constructor" ``` ### 以表達式定義生成器 ``` const foo = function* () { yield 10; yield 20; }; const bar = foo();console.log(bar.next()); // {value: 10, done: false} ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-generator-function-definitions | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. Firefox 規範註記 ------------ #### Generators and iterators in Firefox versions before 26 Older Firefox versions implement an older version of the generators proposal. In the older version, generators were defined using a regular `function` keyword (without an asterisk) among other differences. See Legacy generator function (en-US) for further information. #### `IteratorResult` object returned instead of throwing Starting with Gecko 29, the completed generator function no longer throws a `TypeError` (en-US) "generator has already finished". Instead, it returns an `IteratorResult` object like `{ value: undefined, done: true }` (Firefox bug 958951). 參見 -- * `function* expression` (en-US) * `GeneratorFunction` (en-US) object * 迭代協議 * `yield` (en-US) * `yield*` (en-US) * `Function` (en-US) object * `function declaration` (en-US) * `function expression` (en-US) * `Functions and function scope` (en-US) * Other web resources: + Regenerator an ES2015 generator compiler to ES5 + Forbes Lindesay: Promises and Generators: control flow utopia — JSConf EU 2013 + Task.js + Iterating generators asynchronously
break - JavaScript
break ===== **break 陳述句**會中斷目前的迭代、`switch` 或 `label` 陳述句,並將程式流程轉到被中斷之陳述句後的陳述句。 嘗試一下 ---- 語法 -- ``` break [label]; ``` `label` 可選的。欲中斷陳述句的標籤 (label) 識別。若不是要中斷迭代或 `switch`,則需加此參數。 說明 -- 中斷陳述 `break` 可加上標籤 (label) 參數,使其跳出被標籤的陳述語句。此中斷陳述 `break` 必須被包含在被標籤的陳述語句中。被標籤的陳述語句可被添加於任一個區塊 (block (en-US)) 前,而非限定在迴圈陳述。 範例 -- 下面函式包含一個中斷陳述 `break` ,當 `i` 值為 3 時,中斷 `while` 迴圈,並回傳 `3 * x` 。 ```js function testBreak(x) { var i = 0; while (i < 6) { if (i == 3) { break; } i += 1; } return i \* x; } ``` The following code uses `break` statements with labeled blocks. A `break` statement must be nested within any label it references. Notice that `inner_block` is nested within `outer_block`. ```js outer\_block: { inner\_block: { console.log("1"); break outer_block; // breaks out of both inner\_block and outer\_block console.log(":-("); // skipped } console.log("2"); // skipped } ``` The following code also uses `break` statements with labeled blocks but generates a Syntax Error because its `break` statement is within `block_1` but references `block_2`. A `break` statement must always be nested within any label it references. ```js block\_1: { console.log('1'); break block_2; // SyntaxError: label not found } block\_2: { console.log('2'); } ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-break-statement | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `continue` * `label` * `switch`
while 語法 - JavaScript
while 語法 ======== `while` 語法會執行他的語句,只要指定的條件的求值結果為 true。`while` 語法如下︰ ```js while (condition) statement ``` 如果條件變成 false,就停止執行循環內部的 `statement`,並把控制權移交給循環後面的語句。 條件的測試會發生在執行循環裡的 `statement` 之前。如果返回的條件為 true,就會執行 `statement`,並再次測試條件。如果返回的條件為 false,就停止執行並把控制權移交給 `while` 後面的語句。 若要執行多個語句,就使用區塊語法(`{ ... }`)把這些語句群組化。 範例 1 ---- 以下 `while` 循環會一直反覆直到 `n` 小於 3 為止︰ ```js n = 0; x = 0; while (n < 3) { n++; x += n; } ``` 每一次的反覆,循環便會遞增 `n` 並且把 `n` 的值代入給 `x`。因此,`x` 和 `n` 持有下列的值︰ * 第一次循環以後︰`n` = 1、`x` = 1 * 第二次循環以後︰`n` = 2、`x` = 3 * 第三次循環以後︰`n` = 3、`x` = 6 第三次的循環完成以後,條件 `n` < 3 不再為 true,所以終止循環。 範例 2 ---- 應避免無限循環。確認循環裡的條件最終一定會變成 false。否則循環永遠不會終止。下面的 `while` 循環裡的語句將會永遠執行下去,因為條件永遠不會變成 false︰ ```js while (true) { alert("Hello, world"); } ```
import - JavaScript
import ====== **import** 宣告用於引入由另一個模塊所導出的綁定。被引入的模塊,無論是否宣告`strict mode`,都會處於該模式。`import` 宣告無法用於嵌入式腳本(embedded scripts)。 There is also a function-like dynamic **`import()`**, which does not require scripts of `type="module"`. Dynamic import is useful in situations where you wish to load a module conditionally, or on demand. The static form is preferable for loading initial dependencies, and can benefit more readily from static analysis tools and tree shaking (en-US). 語法 -- ``` import defaultExport from "module-name"; import * as name from "module-name"; import { export } from "module-name"; import { export as alias } from "module-name"; import { export1 , export2 } from "module-name"; import { export1 , export2 as alias2 , [...] } from "module-name"; import defaultExport, { export [ , [...] ] } from "module-name"; import defaultExport, * as name from "module-name"; import "module-name"; ``` `defaultExport` 從模塊要參照過去的預設導出名。 `module-name` 要導入的模塊名。通常包含 `.js` 模塊文件的相對或絕對路徑名。請確認你的開發環境,某些 bundler 會允許或要求你加入副檔名。只允許使用單引號和雙引號字符串。 `name` 參照導入時,會用做 namespace 種類的模塊名。 `export, exportN` 導出要被引入時,要用的名號。 `alias, aliasN` 別名,重新命名被 import 進來的 js 稱呼。 敘述 -- `name` 參數能將模塊物件(module object)名用於 namespace 種類,以便各導出能參照之。`export` 參數會在引用 `import * as name` 語法時,指定 individual named export。以下示例將展示語法的簡例。 ### 引入整個模塊的內容 本例在當前作用域插入了 `myModule` 變數,並把所有來自 `/modules/my-module.js` 檔案的模塊導出。 ```js import \* as myModule from "/modules/my-module.js"; ``` 這裡會用到指定的模塊名(在此為 myModule)訪問導出來的命名空間。例如說引入模塊有 `doAllTheAmazingThings()` 的話,就可以這麼寫: ```js myModule.doAllTheAmazingThings(); ``` ### 從模塊引入單一導出 給定由 `my-module` 導出的模塊,稱作 `myExport` 物件與數值,無論是顯性(因為整個模塊被導出了)與隱性(使用 `export` 宣告),這裡就在當前的作用域插入 `myExport`。 ```js import { myExport } from "/modules/my-module.js"; ``` ### 從模塊引入數個導出 例在當前作用域插入了 `foo` 與 `bar`。 ```js import { foo, bar } from "/modules/my-module.js"; ``` ### 使用便利的 alias 引入或導出 在引入時,可以重新命名導出的模塊。例如說,這裡就就在目前作用域插入 `shortName` 變數。 ```js import { reallyReallyLongModuleExportName as shortName } from "/modules/my-module.js"; ``` ### 引入時重命名數個導出 使用別名(aliases)以便引入或導出模塊 ```js import { reallyReallyLongModuleExportName as shortName, anotherLongModuleName as short, } from "/modules/my-module.js"; ``` ### 僅作為副作用引入模塊 僅作為副作用(side effect)引入整個模塊,而不直接引入任何東西。這樣會在不引入實際數值的情況下,執行整個模塊的程式。 ```js import "/modules/my-module.js"; ``` ### 引入預設 你可以引入預設好的 `export`,無論他屬於物件、函式、還是類別。`import` 宣告可以接著引入該預設。 最簡單的預設引入: ```js import myDefault from "/modules/my-module.js"; ``` It is also possible to use the default syntax with the ones seen above (namespace imports or named imports). In such cases, the default import will have to be declared first. For instance: ```js import myDefault, \* as myModule from "/modules/my-module.js"; // myModule used as a namespace ``` 或是: ```js import myDefault, { foo, bar } from "/modules/my-module.js"; // specific, named imports ``` ### 動態引入 `import` 關鍵字也能透過函式呼叫引入之。在這種情況下,該函式回傳 promise。 ```js import("/modules/my-module.js").then((module) => { // 在模塊內作點事情 }); ``` 這方法也支援關鍵字 await。 ```js let module = await import("/modules/my-module.js"); ``` 示例 -- 引用次要模塊以協助程式執行 AJAX JSON 請求。 ### 模塊:file.js ```js function getJSON(url, callback) { let xhr = new XMLHttpRequest(); xhr.onload = function () { callback(this.responseText); }; xhr.open("GET", url, true); xhr.send(); } export function getUsefulContents(url, callback) { getJSON(url, (data) => callback(JSON.parse(data))); } ``` ### 主要程式:main.js ```js import { getUsefulContents } from "/modules/file.js"; getUsefulContents("http://www.example.com", (data) => { doSomethingUseful(data); }); ``` ### 動態引入 This example shows how to load functionality on to a page based on a user action, in this case a button click, and then call a function within that module. This is not the only way to implement this functionality. The `import()` function also supports `await`. ```js const main = document.querySelector("main"); for (const link of document.querySelectorAll("nav > a")) { link.addEventListener("click", (e) => { e.preventDefault(); import("/modules/my-module.js") .then((module) => { module.loadPageInto(main); }) .catch((err) => { main.textContent = err.message; }); }); } ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-imports | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `export` * Previewing ES6 Modules and more from ES2015, ES2016 and beyond * ES6 in Depth: Modules, Hacks blog post by Jason Orendorff * ES modules: A cartoon deep-dive, Hacks blog post by Lin Clark * Axel Rauschmayer's book: "Exploring JS: Modules"
區塊 - JavaScript
區塊 == 總覽 -- 區塊陳述用來組合零個或多個陳述。我們使用一對大括號 { } 以界定區塊。 | 陳述句 | | --- | | Implemented in | JavaScript 1.0 | | ECMAScript edition | ECMA-262 1st edition | 語法 -- ``` { 陳述_1 陳述_2 ... 陳述_n } ``` ### 參數 `陳述_1`, `陳述_2`, `陳述_n` 區塊陳述中的陳述句群。 說明 -- 區塊陳述通常配合流程控制陳述(如 `if`、`for`、`while`)一併使用。 #### `var` 使用`var`區塊中定義的變數,其存取範圍是整個整個函式或是腳本,即為 Execution Context 的範圍中。 ```js var x = 1; { var x = 2; } alert(x); // outputs 2 ``` 輸出結果是 2。因為 var 是宣告於整個腳本範圍中。 #### `let` 和 `const` 當使用`let`或是`const`進行宣告時,其存取範圍是只有本身定義的區塊中。 ```js let x = 1; { let x = 2; } console.log(x); // logs 1 ``` #### `function` 當 function 被呼叫時,會建立此 function 的 Execution Context,因此在 function 區塊使用`var`整個 function 區塊中都可對其進行存取。 ```js function foo() { { var a = "var"; { let a = "let"; console.log(a); // let } } console.log(a); // var } foo(); ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-block | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
預設參數( Default parameters ) - JavaScript
預設參數( Default parameters ) ========================== **函式預設參數** 允許沒有值傳入或是傳入值為 `undefined 的情況下,參數能以指定的預設值初始化。` 語法 -- ``` function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) { 要執行的程序 } ``` 說明 -- 在 JavaScript 中,函式的參數預設值都為 ``undefined` (en-US) 。然而,指定不同的預設值可能在一些場景很有用。這也是函式參數預設值可以幫上忙的地方。` 以往設定預設值有個普遍方法:在函式的內容裡檢查傳入參數是否為 `undefined ,如果是的話,爲他指定一個值。如下列範例,若函式被呼叫時,並沒有提供 b 的值,它的值就會是 undefined,在計算 a*b 時,以及呼叫 multiply 時,就會回傳 NaN。然而這在範例的第二行被阻止了:`: ```js function multiply(a, b) { b = typeof b !== "undefined" ? b : 1; return a \* b; } multiply(5, 2); // 10 multiply(5, 1); // 5 multiply(5); // 5 ``` 有了 ES2015 的預設參數,再也不用於函式進行檢查了,現在只要簡單的在函式的起始處為 b 指定 1 的值: ```js function multiply(a, b = 1) { return a \* b; } multiply(5, 2); // 10 multiply(5, 1); // 5 multiply(5); // 5 ``` 範例 -- ### 傳入 `undefined` 這邊第二段函式呼叫中,僅管第二個傳入參數在呼叫時明確地指定為 undefined(雖不是 null),其顏色參數的值是預設值(rosybrown)。 ```js function setBackgroundColor(element, color = "rosybrown") { element.style.backgroundColor = color; } setBackgroundColor(someDiv); // color set to 'rosybrown' setBackgroundColor(someDiv, undefined); // color set to 'rosybrown' too setBackgroundColor(someDiv, "blue"); // color set to 'blue' ``` ### 呼叫時賦予值 跟 Python 等語言不同的地方是,先前預設的代數值會拿來進行函式內的程序,也因此在函式呼叫的時候,會建立新物件。 ```js function append(value, array = []) { array.push(value); return array; } append(1); //[1] append(2); //[2], 而非 [1, 2] ``` 諸如此類的做法,也適用在函式和變量。 ```js function callSomething(thing = something()) { return thing; } function something() { return "sth"; } callSomething(); //sth ``` ### 預設的參數中,先設定的可提供之後設定的使用 先前有碰到的參數,後來的即可使用。 ```js function singularAutoPlural( singular, plural = singular + "們", rallyingCry = plural + ",進攻啊!!!", ) { return [singular, plural, rallyingCry]; } //["壁虎","壁虎們", "壁虎,進攻啊!!!"] singularAutoPlural("壁虎"); //["狐狸","火紅的狐狸們", "火紅的狐狸們,進攻啊!!!"] singularAutoPlural("狐狸", "火紅的狐狸們"); //["鹿兒", "鹿兒們", "鹿兒們 ... 有所好轉"] singularAutoPlural( "鹿兒", "鹿兒們", "鹿兒們平心靜氣的 \ 向政府請願,希望事情有所好轉。", ); ``` This functionality is approximated in a straight forward fashion and demonstrates how many edge cases are handled. ```js function go() { return ":P"; } function withDefaults( a, b = 5, c = b, d = go(), e = this, f = arguments, g = this.value, ) { return [a, b, c, d, e, f, g]; } function withoutDefaults(a, b, c, d, e, f, g) { switch (arguments.length) { case 0: a; case 1: b = 5; case 2: c = b; case 3: d = go(); case 4: e = this; case 5: f = arguments; case 6: g = this.value; default: } return [a, b, c, d, e, f, g]; } withDefaults.call({ value: "=^\_^=" }); // [undefined, 5, 5, ":P", {value:"=^\_^="}, arguments, "=^\_^="] withoutDefaults.call({ value: "=^\_^=" }); // [undefined, 5, 5, ":P", {value:"=^\_^="}, arguments, "=^\_^="] ``` ### 函式內再定義函式 Introduced in Gecko 33. Functions declared in the function body cannot be referred inside default parameters and throw a `ReferenceError` (en-US) (currently a `TypeError` (en-US) in SpiderMonkey, see Firefox bug 1022967). Default parameters are always executed first, function declarations inside the function body evaluate afterwards. ```js // 行不通的! 最後會丟出 ReferenceError。 function f(a = go()) { function go() { return ":P"; } } ``` ### Parameters without defaults after default parameters Prior to Gecko 26, the following code resulted in a `SyntaxError` (en-US). This has been fixed in Firefox bug 777060 and works as expected in later versions. Parameters are still set left-to-right, overwriting default parameters even if there are later parameters without defaults. ```js function f(x = 1, y) { return [x, y]; } f(); // [1, undefined] f(2); // [2, undefined] ``` ### Destructured parameter with default value assignment You can use default value assignment with the destructuring assignment notation: ```js function f([x, y] = [1, 2], { z: z } = { z: 3 }) { return x + y + z; } f(); // 6 ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-function-definitions | 瀏覽器的兼容性 ------- BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * Original proposal at ecmascript.org
getter - JavaScript
getter ====== **`get`** 語法會將物件屬性,綁定到屬性被檢索時,所呼叫的函式。 嘗試一下 ---- 語法 -- ``` {get prop() { ... } } {get [expression]() { ... } } ``` ### 參數 `prop` 要綁定到給定函式的名稱。 expression 自 ECMAScript 2015 開始,可以用計算屬性名稱(computed property name),綁定到給定函式。 敘述 -- 有時候,物件的屬性可能需要回傳動態數值、或要在不使用明確的方法呼叫下,反映出內部變數的狀態。在 JavaScript 可以用 *getter* 達到這個目的。儘管可以用 getter 與 setter 的關聯建立虛擬屬性的類型,但 getter 無法被綁定到同時擁有實際數值的屬性。 使用 `get` 語法時,請注意以下情況: * 可以擁有一個以數字或字串為代表的標示符; * 最少要有零個參數(請參見 Incompatible ES5 change: literal getter and setter functions must now have exactly zero or one arguments 的詳細資料) * 不能以有另一個 `get` 的 object literal、或相同屬性入口(data entry)的 data 形式出現(不能使用 `{ get x() { }, get x() { } }` and `{ x: ..., get x() { } }`)。 getter 可以用 `delete` 操作符移除。 示例 -- ### 在物件初始器(object initializers)內定義新物件的 getter 這程式碼將給 `obj` 物件建立虛擬屬性 `latest`,它會回傳 `log` 陣列的最後一個單元。 ```js var obj = { log: ["example", "test"], get latest() { if (this.log.length == 0) return undefined; return this.log[this.log.length - 1]; }, }; console.log(obj.latest); // "test". ``` 請注意 `latest` 不會因為數值被指派而改變。 ### 使用 `delete` 操作符移除 getter 如果想移除 getter,可以使用 `delete` 完成之: ```js delete obj.latest; ``` ### 使用 `defineProperty` 給現有物件定義 getter 若想在任何時候給現有物件添增 getter,請使用 `Object.defineProperty()`。 ```js var o = { a: 0 }; Object.defineProperty(o, "b", { get: function () { return this.a + 1; }, }); console.log(o.b); // Runs the getter, which yields a + 1 (which is 1) ``` ### 使用計算屬性名 ```js var expr = "foo"; var obj = { get [expr]() { return "bar"; }, }; console.log(obj.foo); // "bar" ``` ### Smart / self-overwriting / lazy getters Getter 提供了定義物件屬性的方法,但它本身並不會去自動計算,直到想訪問它。除非需要用 getter,否則數值計算會被延緩;如果不需要用到 getter,那就永遠無須支付計算的開銷。 針對屬性值 lazy 或 delay、並暫存以留作未來訪問的最佳化技巧稱作 **smart 或 memoized getter**:初次計算時會呼叫 getter、接著被暫存以便在不重算的情況下做後續訪問。這種技巧在以下情況會派上用場: * 如果數值開銷很昂貴(例如需要大量 RAM 或 CPU 時間、產生 worker 執行緒、檢索遠端文件等) * 如果現在並不需要數值:可能是現在用不到、或在某些情況下完全用不到。 * 如果使用的話,該數值會被訪問數次、且該數值永遠不會更改、或不應該更改。 也就是說,出於 getter 不會重新計算的理由,不要針對數值預期會改變的屬性,使用 lazy getter。 下例的物件擁有作為自己的屬性的 getter。在取得該屬性後,它會從物件被移除、並以隱式數值屬性重新增加、最後回傳之。 ```js get notifier() { delete this.notifier; return this.notifier = document.getElementById('bookmarked-notification-anchor'); }, ``` 針對 Firefox 程式碼,另請參見定義 `defineLazyGetter()` 函式的 XPCOMUtils.jsm 程式模塊。 ### `get` 與 `defineProperty` 在使用 `classes` 時,儘管 `get` 關鍵字與 `Object.defineProperty()` 會出現相同結果,但其中有微妙的差異。 在使用 `get` 時,屬性會在物件的原型被定義;而在使用 `Object.defineProperty()` 時,屬性會在被套用的實例內定義。 ```js class Example { get hello() { return "world"; } } const obj = new Example(); console.log(obj.hello); // "world" console.log(Object.getOwnPropertyDescriptor(obj, "hello")); // undefined console.log( Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), "hello"), ); // { configurable: true, enumerable: false, get: function get hello() { return 'world'; }, set: undefined } ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-method-definitions | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * setter * `delete` * `Object.defineProperty()` * `Object.prototype.__defineGetter__()` (en-US) * `Object.prototype.__defineSetter__()` (en-US) * JavaScript 教學的定義 Getter 與 Setter (en-US)
箭頭函式 - JavaScript
箭頭函式 ==== **箭頭函式運算式**(arrow function expression)擁有比函式運算式 (en-US)還簡短的語法。它沒有自己的 `this`、arguments (en-US)、super、new.target (en-US) 等語法。本函式運算式適用於非方法的函式,但不能被用作建構式(constructor)。 嘗試一下 ---- 基本語法 ---- ``` (參數1, 參數2, …, 參數N) => { 陳述式; } (參數1, 參數2, …, 參數N) => 表示式; // 等相同(參數1, 參數2, …, 參數N) => { return 表示式; } // 只有一個參數時,括號才能不加: (單一參數) => { 陳述式; } 單一參數 => { 陳述式; } //若無參數,就一定要加括號: () => { statements } ``` 進階語法 ---- ``` // 用大括號將內容括起來,返回一個物件字面值表示法: params => ({foo: bar}) // 支援其餘參數與預設參數 (param1, param2, ...rest) => { statements } (param1 = defaultValue1, param2, …, paramN = defaultValueN) => { statements } // 也支援 parameter list 的解構 var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c; f(); // 6 ``` 說明 -- 也可參閱 "ES6 In Depth: Arrow functions" on hacks.mozilla.org。 箭頭函式有兩個重要的特性:更短的函式寫法與 `this` 變數的非綁定。 ### 更短的函式寫法 ```js var elements = ["Hydrogen", "Helium", "Lithium", "Beryllium"]; // 這段函式會輸出[8, 6, 7, 9]這個陣列 elements.map(function (element) { return element.length; }); // 上方這種一般的函式,可以被改寫成下方的箭頭函式 elements.map((element) => { return element.length; }); // [8, 6, 7, 9] // 如果輸入的參數只有一個,我們可以移除掉外面的括號 elements.map((element) => { return element.length; }); // [8, 6, 7, 9] // 當箭頭函式裡的內容只有'return'的時候,我們可以拿掉return和外面的大括號 elements.map((element) => element.length); // [8, 6, 7, 9] // 在這個範例中,因為我們只需要length這個屬性,所以也可以使用解構賦值: // 下方的'length'對應到我們想取得的屬性,而'lengthFooBArX'只是很普通的變數名稱, // 可以被任意修改成你想要的名字 elements.map(({ length: lengthFooBArX }) => lengthFooBArX); // [8, 6, 7, 9] // 上面這種解構賦值之後的參數也可以被改寫為下面這樣。但要注意的是,在這個範例中, // 我們不是要指定'length'這個值給一個虛構的屬性,而是這個變數的名稱'length'本身就是 // 用來當成我們想從物件上取得的屬性 elements.map(({ length }) => length); // [8, 6, 7, 9] ``` ### `this` 不分家 在有箭頭函數之前,每個新函式是依據如何被呼叫來定義自己的 `this` 變數 例如: * 在建構子時是一個新物件 * 在呼叫嚴格模式函數時是 undefined * 以物件方法呼叫時則為基礎物件 * 等等.... 事實證明這對物件導向程式設計來說並不理想。 ```js function Person() { // Person() 建構式將 this 定義為它自己的一個實體 this.age = 0; setInterval(function growUp() { // 在非嚴格模式下, growUp() 函式把 this 定義為全域物件 // (因為那是 growUp()執行的所在), // 與 Person() 建構式所定義的 this 有所不同 this.age++; }, 1000); } var p = new Person(); ``` 在 ECMAScript 3/5 裡面,有關 `this` 的問題,可以透過指派 `this` 值給可以關閉的變數解決。 ```js function Person() { var self = this; // 有些人喜歡 `that` 而不是 `self`. // 選好一種取法後始終如一 self.age = 0; setInterval(function growUp() { // 這個 callback 參考 `self` 變數,為預期中的物件。 self.age++; }, 1000); } ``` 或者透過 bind 函式來綁定 `this` 變數到指定函式(以上面為例,就是 `growUp()` 函式)。 箭頭函式並不擁有自己的 `this 變`數`;`使用的 this `值來自`封閉的文本上下文,也就是說,箭頭函式遵循常規變量查找規則。因此,如果在當前範圍中搜索不到 this 變量時,他們最終會尋找其封閉範圍。 因此,在以下程式碼內,傳遞給 `setInterval` 的 箭頭函式中的`this` ,會與封閉函式的 `this` 值相同: ```js function Person() { this.age = 0; setInterval(() => { this.age++; // |this| 適切的參考了Person建構式所建立的物件 }, 1000); } var p = new Person(); ``` #### 和嚴格模式的關係 由於 `this` 變數具有詞彙上綁定意義,所以嚴格模式的宣告對 `this` 的作用將被忽略。 ```js var f = () => { "use strict"; return this; }; f() === window; // 或是 global 物件 ``` 但嚴格模式的其他作用依舊存在。 #### 由 call 與 apply 函式呼叫 由於箭頭函式並沒有自己的 `this`,所以透過 `call()` 或 `apply()` 呼叫箭頭函式只能傳入參數。`thisArg` 將會被忽略。 ```js var adder = { base: 1, add: function (a) { var f = (v) => v + this.base; return f(a); }, addThruCall: function (a) { var f = (v) => v + this.base; var b = { base: 2, }; return f.call(b, a); }, }; console.log(adder.add(1)); // 顯示 2 console.log(adder.addThruCall(1)); // 依舊顯示 2 ``` ### 不綁定 `arguments` 箭頭函式並沒有自己的 `arguments` 物件 (en-US)。所以在此例中,`arguments` 只是參考到 enclosing 作用域裡面的相同變數: ```js var arguments = [1, 2, 3]; var arr = () => arguments[0]; arr(); // 1 function foo(n) { var f = () => arguments[0] + n; // foo's implicit arguments binding. arguments[0] is n return f(); } foo(1); // 2 ``` 大多時候,使用其餘參數 是取代 `arguments` 物件的較好方式。 ```js function foo(n) { var f = (...args) => args[0] + n; return f(10); } foo(1); // 11 ``` ### 將箭頭函式撰寫為方法 如同前述,箭頭函式運算式最適合用在非方法的函式。來看看如果要把它們當成方法來用,會發生什麼事: ```js "use strict"; var obj = { i: 10, b: () => console.log(this.i, this), c: function () { console.log(this.i, this); }, }; obj.b(); // 印出 undefined, Window {...} (or the global object) obj.c(); // 印出 10, Object {...} ``` 箭頭函式並沒有自己的 `this`。另一個例子與 `Object.defineProperty()` 有關: ```js "use strict"; var obj = { a: 10, }; Object.defineProperty(obj, "b", { get: () => { console.log(this.a, typeof this.a, this); // undefined, 'undefined', Window {...} (or the global object) return this.a + 10; // represents global object 'Window', therefore 'this.a' returns 'undefined' }, }); ``` ### 使用 `new` 運算子 箭頭函式不可作為建構式使用;若使用於建構式,會在使用 `new` 時候拋出錯誤。 ```js var Foo = () => {}; var foo = new Foo(); // TypeError: Foo is not a constructor ``` ### 使用 `prototype` 屬性 箭頭函式並沒有原型(`prototype`)屬性。 ```js var Foo = () => {}; console.log(Foo.prototype); // undefined ``` ### 使用關鍵字 `yield` `yield` (en-US) 關鍵字無法用於箭頭函式的 body(except when permitted within functions further nested within it)。因此,箭頭函式無法使用 generator。 函式主體(Function body) ------------------- 箭頭函式可以變成 concise body 或者平常使用的 block body。 在 concise body 裡面只需要輸入運算式,就會附上內建的回傳。在 block body 裡面就必須附上明確的 `return` 宣告。 ```js var func = (x) => x \* x; // concise 語法會內建 "return" var func = (x, y) => { return x + y; }; // block body 需要明確的 "return" ``` 回傳物件字面值 ------- 請注意只使用 `params => {object:literal}` 並不會按照期望般回傳物件字面值(object literal)。 ```js var func = () => { foo: 1 }; // Calling func() returns undefined! var func = () => { foo: function() {} }; // SyntaxError: Unexpected token ( ``` 因為在大括弧(`{}`)裡面的文字會被解析為有序宣告(例如 `foo` 會被當作標記(label)、而不是物件的 key ) 要記得把物件字面值包在圓括弧內。 ```js var func = () => ({ foo: 1 }); var func = () => ({ foo: function () {} }); ``` 換行 -- 箭頭函式不可以在參數及箭頭間包含換行。 ```js var func = () => 1; // SyntaxError: expected expression, got '=>' ``` Parsing order ------------- 箭頭函式的箭頭儘管不是操作符,但藉著運算子優先等級,箭頭函式有著和普通函式不相同的特殊解析規則。 ```js let callback; callback = callback || function() {}; // ok callback = callback || () => {}; // SyntaxError: invalid arrow-function arguments callback = callback || (() => {}); // ok ``` 更多範例 ---- ```js // 回傳 undefined 的箭頭函式 let empty = () => {}; (() => "foobar")(); // 回傳 "foobar" var simple = (a) => (a > 15 ? 15 : a); simple(16); // 15 simple(10); // 10 let max = (a, b) => (a > b ? a : b); // Easy array filtering, mapping, ... var arr = [5, 6, 13, 0, 1, 18, 23]; var sum = arr.reduce((a, b) => a + b); // 66 var even = arr.filter((v) => v % 2 == 0); // [6, 0, 18] var double = arr.map((v) => v \* 2); // [10, 12, 26, 0, 2, 36, 46] ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-arrow-function-definitions | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參閱 -- * "ES6 In Depth: Arrow functions" on hacks.mozilla.org
其餘參數 - JavaScript
其餘參數 ==== **其餘參數(rest parameter)** 語法可以讓我們表示不確定數量的參數,並將其視為一個陣列。 語法 -- ```js function f(a, b, ...theArgs) { // ... } ``` 描述 -- 如果函式的最後一個命名參數以 `...` 開頭,它會被視為一個陣列。該陣列的元素會被置於索引從 `0`(含)到的 `theArgs.length`(不含)位置,並且被視為一個函式的參數。 在上面的範例中,`theArgs` 會將函式 f 中第三個(含)以後的參數收集起來。 ### 其餘參數和 `arguments` 物件的差異 以下是其餘參數和 `arguments 物件`三個主要的差異: * 其餘參數是 `arguments` 物件被傳入到函式的時候,還沒被指定變數名稱的引數。 * `arguments` 物件不是一個實際的陣列,而 rest parameter 是陣列的實體,即 `sort`、`map`、`forEach` (en-US) 或 `pop` 可以直接在其餘參數被調用。 * `arguments` 物件自身有額外的功能,例如 `callee` 屬性。 ### 將參數轉成陣列 其餘參數被介紹作為取代用 arguments 寫的範例程式。 ```js // 在有其餘參數之前,你可能見過下面的程式碼: function f(a, b) { var args = Array.prototype.slice.call(arguments, f.length); // f.length 表示 arguments 的數量 // … } // 現在可以寫成這樣 function f(a, b, ...args) {} ``` ### 解構其餘參數 rest parameters 其餘參數可以被解構,換句話說,可以把這個陣列解開,並將各個元素取出成為個別的變數。請參考解構賦值。 ```js function f(...[a, b, c]) { return a + b + c; } f(1); // NaN (b 和 c 都是 undefined) f(1, 2, 3); // 6 f(1, 2, 3, 4); // 6 (第四個參數不會被解構,因為解構式只有三個定義好的變數名稱) ``` 範例 -- 因為 `theArgs` 是一個陣列,所以它會有 `length` 屬性,作為表示參數數量: ```js function fun1(...theArgs) { console.log(theArgs.length); } fun1(); // 0 fun1(5); // 1 fun1(5, 6, 7); // 3 ``` 在接下來的範例中,其餘參數被用來收集第一個之後的所有引數並存在陣列中。 在這個陣列裡的每個元素(數字),都會和第一個參數相乘後取代原本的元素,最後再將取代元素後的陣列回傳。 ```js function multiply(multiplier, ...theArgs) { return theArgs.map(function (element) { return multiplier \* element; }); } var arr = multiply(2, 1, 2, 3); console.log(arr); // [2, 4, 6] ``` 下列範例展示 `Array` 的方法可以在其餘參數上被使用,但 `arguments` 則不行。 ```js function sortRestArgs(...theArgs) { var sortedArgs = theArgs.sort(); return sortedArgs; } console.log(sortRestArgs(5, 3, 7, 1)); // 顯示 1, 3, 5, 7 function sortArguments() { var sortedArgs = arguments.sort(); return sortedArgs; // 因為前一行會因為 arguments 沒有sort()這個方法而造成TypeError,所以永遠不會執行此行。 } console.log(sortArguments(5, 3, 7, 1)); // 會拋出 TypeError (arguments.sort is not a function) ``` 為了要在 `arguments` 物件上使用 `Array` 的方法,可以將它轉換成真的 `Array` 實體,或者以 `apply()` 直接調用需要的方法。 ```js function sortArguments() { var args = Array.from(arguments); var sortedArgs = args.sort(); return sortedArgs; } console.log(sortArguments(5, 3, 7, 1)); // 顯示 1, 3, 5, 7 ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-function-definitions | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * Spread operator (en-US) (also 『`...`』) * Arguments object (en-US) * Array * Functions (en-US) * Original proposal at ecmascript.org * JavaScript arguments object and beyond * Destructuring assignment
setter - JavaScript
setter ====== **`set`** 語法會在物件屬性被嘗試定義時,將其屬性綁定到要呼叫的函式內。 嘗試一下 ---- 語法 -- ``` {set prop(val) { . . . }} {set [expression](val) { . . . }} ``` ### 參數 `prop` 要綁定到給定函式的屬性名。 `val` 變數別名,該變數擁有要被嘗試安插到 `prop` 的數值。 expression 從 ECMAScript 2015 開始,可以使用計算屬性名(computed property name)表達式,綁定到給定函式。 描述 -- JavaScript 的 setter 能在嘗試修改指定屬性時,執行給定函式。Setter 最常用於和 getter 一同建立虛擬屬性(pseudo-property)。你不可能給同一個屬性賦予 setter 與實際值。 使用 `set` 語法時,請注意以下情況: * 可以擁有一個以數字或字串為代表的標示符; * 最少要有一個參數(請參見 Incompatible ES5 change: literal getter and setter functions must now have exactly zero or one arguments 的詳細資料); * 不能以有另一個 `set` 的 object literal、或相同屬性入口(data entry)的 data 形式出現(不能使用 `{ set x(v) { }, set x(v) { } }` and `{ x: ..., set x(v) { } }`) `delete` 操作符可移除 setter。 示例 -- ### 在物件初始器的新物件定義 setter 這裡會給物件 `language` 定義稱為 `current` 的虛擬屬性。在指派數值時 `log` 會和該值一同更新: ```js var language = { set current(name) { this.log.push(name); }, log: [], }; language.current = "EN"; console.log(language.log); // ['EN'] language.current = "FA"; console.log(language.log); // ['EN', 'FA'] ``` 請注意 `current` is not defined and any attempts to access it will result in `undefined`. ### 使用 `delete` 操作符移除 setter 若想移除 setter 的話,可以直接使用 `delete`: ```js delete o.current; ``` ### 針對已存在屬性的 setter 使用 `defineProperty` To append a setter to an existing object later at any time, use `Object.defineProperty()`. ```js var o = { a: 0 }; Object.defineProperty(o, "b", { set: function (x) { this.a = x / 2; }, }); o.b = 10; // Runs the setter, which assigns 10 / 2 (5) to the 'a' property console.log(o.a); // 5 ``` ### 使用計算屬性名 ```js var expr = "foo"; var obj = { baz: "bar", set [expr](v) { this.baz = v; }, }; console.log(obj.baz); // "bar" obj.foo = "baz"; // 跑 setter console.log(obj.baz); // "baz" ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-method-definitions | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * getter * `delete` * `Object.defineProperty()` * `Object.prototype.__defineGetter__()` (en-US) * `Object.prototype.__defineSetter__()` (en-US) * JavaScript 教學的定義 Getters 與 Setters (en-US)
方法定義 - JavaScript
方法定義 ==== 自 ECMAScript 2015 開始,引入了一種於物件初始器(objects initializers)中定義方法的簡短語法。是一個將函式指派予方法名稱的簡便方式。 嘗試一下 ---- 語法 -- ``` var obj = { property( parameters… ) {}, *generator( parameters… ) {}, async property( parameters… ) {}, async* generator( parameters… ) {}, // with computed keys: [property]( parameters… ) {}, *[generator]( parameters… ) {}, async [property]( parameters… ) {}, // compare getter/setter syntax: get property() {}, set property(value) {} }; ``` 說明 -- 這個簡短的語法和在 ECMAScript 2015 引入 getter 以及 setter 類似。 請看以下程式碼: ```js var obj = { foo: function () { /\* code \*/ }, bar: function () { /\* code \*/ }, }; ``` 你可以把它縮減為: ```js var obj = { foo() { /\* code \*/ }, bar() { /\* code \*/ }, }; ``` ### 產生器方法 產生器方法(Generator method)也可以透過簡短語法定義之。用的時候: * 簡短語法的星號(\*)必須放在產生器方法的屬性名前面。也就是說 `* g(){}` 能動但 `g *(){}` 不行; * 非產生器方法的定義可能不會有 `yield` 關鍵字。也就是說過往的產生器函式 (en-US)動不了、並拋出`SyntaxError` (en-US)。Always use `yield` in conjunction with the asterisk (\*). ```js // Using a named property var obj2 = { g: function\* () { var index = 0; while (true) yield index++; }, }; // The same object using shorthand syntax var obj2 = { \*g() { var index = 0; while (true) yield index++; }, }; var it = obj2.g(); console.log(it.next().value); // 0 console.log(it.next().value); // 1 ``` ### Async 方法 Async 方法 也可以透過簡短語法定義。 ```js // Using a named property var obj3 = { f: async function () { await some_promise; }, }; // The same object using shorthand syntax var obj3 = { async f() { await some_promise; }, }; ``` ### Async generator methods Generator methods can also be async. ```js var obj4 = { f: async function\* () { yield 1; yield 2; yield 3; }, }; // The same object using shorthand syntax var obj4 = { async \*f() { yield 1; yield 2; yield 3; }, }; ``` ### Method definitions are not constructable All method definitions are not constructors and will throw a `TypeError` (en-US) if you try to instantiate them. ```js var obj = { method() {}, }; new obj.method(); // TypeError: obj.method is not a constructor var obj = { \*g() {}, }; new obj.g(); // TypeError: obj.g is not a constructor (changed in ES2016) ``` 範例 -- ### Simple test case ```js var obj = { a: "foo", b() { return this.a; }, }; console.log(obj.b()); // "foo" ``` ### Computed property names The shorthand syntax also supports computed property names. ```js var bar = { foo0: function () { return 0; }, foo1() { return 1; }, ["foo" + 2]() { return 2; }, }; console.log(bar.foo0()); // 0 console.log(bar.foo1()); // 1 console.log(bar.foo2()); // 2 ``` 規範 -- | Specification | | --- | | ECMAScript Language Specification # sec-method-definitions | 瀏覽器相容性 ------ BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data. 參見 -- * `get` * `set` * Lexical grammar
RangeError: invalid array length - JavaScript
RangeError: invalid array length ================================ 訊息 -- ``` RangeError: Array length must be a finite positive integer (Edge) RangeError: invalid array length (Firefox) RangeError: Invalid array length (Chrome) RangeError: Invalid array buffer length (Chrome) ``` 錯誤類型 ---- `RangeError`哪裡錯了? ----- 一個無效的陣列長度可能發生於以下幾種情形: * 建立了一個長度為負或大於等於 2^32 的 `Array` 或 `ArrayBuffer` * 將 `Array.length` 屬性設為負值或大於等於 2^32 為什麼 `Array` 和 `ArrayBuffer` 的長度有限? `Array` 和 `ArrayBuffer` 的屬性以一個 32 位元的非負整數表使,因此僅能儲存 0 到 2^32 - 1 的數值。 If you are creating an `Array`, using the constructor, you probably want to use the literal notation instead, as the first argument is interpreted as the length of the `Array`. Otherwise, you might want to clamp the length before setting the length property, or using it as argument of the constructor. 示例 -- ### 無效的案例 ```js new Array(Math.pow(2, 40)); new Array(-1); new ArrayBuffer(Math.pow(2, 32)); // 32-bit system new ArrayBuffer(-1); const a = []; a.length = a.length - 1; // set the length property to -1 const b = new Array(Math.pow(2, 32) - 1); b.length = b.length + 1; // set the length property to 2^32 b.length = 2.5; // set the length property to a floating-point number const c = new Array(2.5); // pass a floating-point number ``` ### 有效的案例 ```js [Math.pow(2, 40)]; // [ 1099511627776 ] [-1]; // [ -1 ] new ArrayBuffer(Math.pow(2, 32) - 1); new ArrayBuffer(Math.pow(2, 33)); // 64-bit systems after Firefox 89 new ArrayBuffer(0); const a = []; a.length = Math.max(0, a.length - 1); const b = new Array(Math.pow(2, 32) - 1); b.length = Math.min(0xffffffff, b.length + 1); // 0xffffffff 是 2^32 - 1 的十六進位表示 // 也可以寫成 (-1 >>> 0) b.length = 3; const c = new Array(3); ``` 參見 -- * `Array` * `Array.length` * `ArrayBuffer`
SyntaxError: return not in function - JavaScript
SyntaxError: return not in function =================================== 訊息 -- ``` SyntaxError: return not in function SyntaxError: yield not in function ``` 錯誤類型 ---- `SyntaxError` (en-US)哪裡錯了? ----- `return` 或 `yield` (en-US) 宣告在函式以外的地方被呼叫。也許少寫了一個大括號?`return` 與 `yield` 宣告必須要寫在函式裡面,因為它們結束(或暫停並恢復)函式的執行,並且回傳了特定值。 實例 -- ```js var cheer = function(score) { if (score === 147) return "Maximum!"; }; if (score > 100) { return "Century!"; } } // SyntaxError: return not in function ``` 乍看之下大括號寫對了,但其實在第一個 `if` 的後面,少了一個 `{`。正確的寫法應該是: ```js var cheer = function (score) { if (score === 147) { return "Maximum!"; } if (score > 100) { return "Century!"; } }; ``` 參見 -- * `return` * `yield` (en-US)
TypeError: "x" has no properties - JavaScript
TypeError: "x" has no properties ================================ 訊息 -- ``` TypeError: null has no properties TypeError: undefined has no properties ``` 錯誤類型 ---- `TypeError` (en-US). 哪裡錯了? ----- `null` (en-US) 與 `undefined` (en-US) 並沒有可訪問的屬性。 示例 -- ```js null.foo; // TypeError: null has no properties undefined.bar; // TypeError: undefined has no properties ``` 參見 -- * `null` (en-US) * `undefined` (en-US)
SyntaxError: redeclaration of formal parameter "x" - JavaScript
SyntaxError: redeclaration of formal parameter "x" ================================================== 訊息 -- ``` SyntaxError: redeclaration of formal parameter "x" (Firefox) SyntaxError: Identifier "x" has already been declared (Chrome) ``` 錯誤類型 ---- `SyntaxError` (en-US)哪裡錯了? ----- 當相同的變數名作為函式的參數、接著又在函式體(function body)內用了 `let` 重複宣告並指派時出現。在 JavaScript 裡面,不允許在相同的函式、或是作用域區塊(block scope)內重複宣告相同的 `let` 變數。 實例 -- 在這裡,「arg」變數的參數被重複宣告。 ```js function f(arg) { let arg = "foo"; } // SyntaxError: redeclaration of formal parameter "arg" ``` If you want to change the value of "arg" in the function body, you can do so, but you do not need to declare the same variable again. In other words: you can omit the `let` keyword. If you want to create a new variable, you need to rename it as conflicts with the function parameter already. ```js function f(arg) { arg = "foo"; } function f(arg) { let bar = "foo"; } ``` 相容性註解 ----- * 在 Firefox 49 之前,這個錯誤被歸為 `TypeError` (en-US)。(Firefox bug 1275240) 參見 -- * `let` * `const` * `var` * 在 JavaScript 教學內宣告變數
TypeError: "x" is not a function - JavaScript
TypeError: "x" is not a function ================================ 訊息 -- ``` TypeError: "x" is not a function ``` 錯誤類型 ---- `TypeError` (en-US). 哪裡錯了? ----- 你想以函式呼叫一個數值,但該數值其實不是函式。程式碼期望你給出函式,但這份期望落空了。 也許打錯了函式的名字?也許呼叫的物件並沒有這個函式?例如說 JavaScript 物件並沒有 `map` 函式,但 JavaScript Array(陣列)物件則有。 許多內建函式都需要回呼(callback)的函式。為了讓下面的方法順利運作,你需要為它們提供函式: * 如果是 `Array` 或 `TypedArray` (en-US) 物件: + `Array.prototype.every()` (en-US)、`Array.prototype.some()` (en-US)、`Array.prototype.forEach()` (en-US)、`Array.prototype.map()`、`Array.prototype.filter()`、`Array.prototype.reduce()`、`Array.prototype.reduceRight()` (en-US)、`Array.prototype.find()` * 如果是 `Map` 與 `Set` 物件: + `Map.prototype.forEach()` (en-US) 與 `Set.prototype.forEach()` (en-US) 實例 -- ### 函式的名字打錯了 這種事太常發生了。下例就有個方法打錯: ```js var x = document.getElementByID("foo"); // TypeError: document.getElementByID is not a function ``` 該函式的正確名字為 `getElementById`: ```js var x = document.getElementById("foo"); ``` ### 函式呼叫到錯誤的物件 某些方法需要你提供回呼的函式,該函式只能作用於特定物件。以本例而言,我們使用的 `Array.prototype.map()` 就只能作用於 `Array` 物件。 ```js var obj = { a: 13, b: 37, c: 42 }; obj.map(function (num) { return num \* 2; }); // TypeError: obj.map is not a function ``` 請改用陣列: ```js var numbers = [1, 4, 9]; numbers.map(function (num) { return num \* 2; }); // Array [ 2, 8, 18 ] ``` 參見 -- * Functions (en-US)
ReferenceError: "x" is not defined - JavaScript
ReferenceError: "x" is not defined ================================== 訊息 -- ``` ReferenceError: "x" is not defined ``` 錯誤類型 ---- `ReferenceError` (en-US). 哪裡錯了? ----- 有個地方參照到不存在的變數了。這個變數需要宣告、或確定在目前腳本、或在 scope (en-US) 裡可用。 **備註:** 如果要使用函式庫(例如 jQuery)的話,請確定在你使用諸如 $ 這樣的函式庫變數前,就已載入完畢。把載入函式庫的 `<script>` 標籤,放在你使用的程式碼之前。 實例 -- ### 變數未宣告 ```js foo.substring(1); // ReferenceError: foo is not defined ``` "foo" 變數在任何地方都沒被定義到。它需要字串使 `String.prototype.substring()` (en-US) 得以運作。 ```js var foo = "bar"; foo.substring(1); // "ar" ``` ### 作用域錯誤 A variable need to be available in the current context of execution. Variables defined inside a function (en-US) cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function ```js function numbers() { var num1 = 2, num2 = 3; return num1 + num2; } console.log(num1); // ReferenceError num1 is not defined. ``` However, a function can access all variables and functions defined inside the scope in which it is defined. In other words, a function defined in the global scope can access all variables defined in the global scope. ```js var num1 = 2, num2 = 3; function numbers() { return num1 + num2; } console.log(num1); // 2 ``` 參閱 -- * Scope (en-US) * Declaring variables in the JavaScript Guide * Function scope in the JavaScript Guide
TypeError: "x" is (not) "y" - JavaScript
TypeError: "x" is (not) "y" =========================== 錯誤類型 ---- `TypeError` (en-US)哪裡錯了? ----- 有一個意想不到的類型。這與 `undefined` (en-US) 或 `null` (en-US) 值經常發生。 另外,某些方法,如 `Object.create()` 或 `Symbol.keyFor()` (en-US) 要求特定類型,即必須提供。 實例 -- ### 無效的情況下 ```js // undefined 和 null 的情況下在其上的子方法不起作用 var foo = undefined; foo.substring(1); // TypeError: foo is undefined var foo = null; foo.substring(1); // TypeError: foo is null // 某些方法可能要求特定類型 var foo = {}; Symbol.keyFor(foo); // TypeError: foo is not a symbol var foo = "bar"; Object.create(foo); // TypeError: "foo" is not an object or null ``` ### 修復問題 為了解決空指針 `undefined` 或 `null` 值,可以使用 typeof 運算符,例如。 operator, for example. ```js if (typeof foo !== "undefined") { // 現在我們知道foo被定義,我們可以繼續進行。 } ``` 參見 -- * `undefined` (en-US) * `null` (en-US)
SyntaxError: missing } after property list - JavaScript
SyntaxError: missing } after property list ========================================== 訊息 -- ``` SyntaxError: missing } after property list ``` 錯誤類型 ---- `SyntaxError` (en-US)何處出錯? ----- 在物件初始化時,語法錯誤。 實際上可能遺漏一個大括號或是逗號。 例如, 同時檢查大括弧以及逗號是否以正確的順序關閉。 縮排或是有規則的排序代碼是有幫助你找出複雜的代碼錯誤。 範例 -- ### 忘記逗號 有時候,在初始化物件時,缺少一個逗號: ```js var obj = { a: 1, b: { myProp: 2 } c: 3 }; ``` Correct would be: ```js var obj = { a: 1, b: { myProp: 2 }, c: 3, }; ``` 參見 -- * Object initializer (en-US)
InternalError: too much recursion - JavaScript
InternalError: too much recursion ================================= 訊息 -- ``` InternalError: too much recursion ``` 錯誤類型 ---- `InternalError` (en-US)哪裡錯了? ----- 一個呼叫自己的函式稱為*遞迴函式*(recursive function)。在某些方面,遞迴和迴圈很像。它們都需要在指定條件(以避免無窮迴圈,或是本例的無窮遞迴)下,重複執行數次相同的程式碼。如果遞迴執行太多次、或成為無窮遞迴的話,JavaScript 就會出現這個錯誤。 實例 -- 以下的遞迴函式,會根據終止條件,而運行十次。 ```js function loop(x) { if (x >= 10) // "x >= 10" 是終止條件 return; // do stuff loop(x + 1); // 遞迴呼叫 } loop(0); ``` 如果把終止條件的次數設得太高,函式就不會運作了: ```js function loop(x) { if (x >= 1000000000000) return; // do stuff loop(x + 1); } loop(0); // InternalError: too much recursion ``` 參見 -- * Recursion * 遞迴函式
使用 Promise - JavaScript
使用 Promise ========== `Promise` 是一個表示非同步運算的最終完成或失敗的物件。由於多數人使用預建立的 Promise,這個導覽會先講解回傳 Promise 的使用方式,之後再介紹如何建立。 基本上,一個 Promise 是一個根據附加給他的 Callback 回傳的物件,以取代傳遞 Callback 到這個函數。 舉例來說,下方的範例若用舊方式應該會有兩個 Callback,並根據成功或失敗來決定使用哪個: ```js function successCallback(result) { console.log("It succeeded with " + result); } function failureCallback(error) { console.log("It failed with " + error); } doSomething(successCallback, failureCallback); ``` 而新作法會回傳一個 Promise,這樣你就可以附加 Callback: ```js let promise = doSomething(); promise.then(successCallback, failureCallback); ``` 再簡單點: ```js doSomething().then(successCallback, failureCallback); ``` 我們稱之為 *非同步函數呼叫*。這個做法有許多好處,我們接下來看看。 保證 -- 不如舊做法,一個 Promise 有這些保證: * Callback 不會在當次的迴圈運行結束前呼叫。 * Callback 用 .then 添加,在非同步運算結束*後*呼叫,像前面那樣。 * 複 Callback 可以透過重複呼叫 .then 達成。 但 Promise 主要的立即好處是串連。 串連 -- 有個常見的需求是依序呼叫兩個以上的非同步函數,我們稱之為建立 *Promise 鏈*。 看看魔術:`then` 函數回傳一個新的 Promise,不同於原本。 ```js let promise = doSomething(); let promise2 = promise.then(successCallback, failureCallback); ``` 或 ```js let promise2 = doSomething().then(successCallback, failureCallback); ``` 第二個 Promise 不只代表 `doSomething()` 完成,還有`successCallback` 或 `failureCallback` ,這兩個非同步函數回傳另一個 Promise。如此一來,任何 Callback 附加給 `promise2` 會被排在 `successCallback` 或`failureCallback` 之後。 基本上,每個 Promise 代表著鏈中另外一個非同步函數的完成。 在古時候,多個非同步函數會使用 Callback 方式,導致波動拳問題: ```js doSomething(function (result) { doSomethingElse( result, function (newResult) { doThirdThing( newResult, function (finalResult) { console.log("Got the final result: " + finalResult); }, failureCallback, ); }, failureCallback, ); }, failureCallback); ``` 有了新方法,我們附加 Callback 到回傳的 Promise 上,來製造 *Promise 鏈*: ```js doSomething() .then(function (result) { return doSomethingElse(result); }) .then(function (newResult) { return doThirdThing(newResult); }) .then(function (finalResult) { console.log("Got the final result: " + finalResult); }) .catch(failureCallback); ``` `then` 的函數是選用的,以及 `catch(failureCallback)` 是 `then(null, failureCallback)` 的簡寫。你也許會想用箭頭函數取代: ```js doSomething() .then((result) => doSomethingElse(result)) .then((newResult) => doThirdThing(newResult)) .then((finalResult) => { console.log(`Got the final result: ${finalResult}`); }) .catch(failureCallback); ``` **注意**:永遠要回傳結果,否則 Callback 不會獲得前一個 Promise 的結果。 ### 獲錯後串接 失敗*後*的串接是可行的,也就是說 `catch` 會非常好用,即使鏈中出錯。看看這個範例: ```js new Promise((resolve, reject) => { console.log("Initial"); resolve(); }) .then(() => { throw new Error("Something failed"); console.log("Do this"); }) .catch(() => { console.log("Do that"); }) .then(() => { console.log("Do this whatever happened before"); }); ``` 他會輸出: ``` Initial Do that Do this whatever happened before ``` 注意「Do this」沒有被輸出,因為「Something failed」錯誤導致拒絕。 錯誤傳遞 ---- 在波動拳狀況中,你可能會看到三次 `failureCallback` ,在 Promise 鏈中只需要在尾端使用一次: ```js doSomething() .then((result) => doSomethingElse(result)) .then((newResult) => doThirdThing(newResult)) .then((finalResult) => console.log(`Got the final result: ${finalResult}`)) .catch(failureCallback); ``` 基本上,一個 Promise 鏈遇到錯誤時會往下尋找 Catch 處理器。這是經過模組化的非同步程式: ```js try { let result = syncDoSomething(); let newResult = syncDoSomethingElse(result); let finalResult = syncDoThirdThing(newResult); console.log(`Got the final result: ${finalResult}`); } catch (error) { failureCallback(error); } ``` 在 ECMAScript 2017 中,在有 `async`/`await` 語法糖的同步程式達到高峰: ```js async function foo() { try { let result = await doSomething(); let newResult = await doSomethingElse(result); let finalResult = await doThirdThing(newResult); console.log(`Got the final result: ${finalResult}`); } catch (error) { failureCallback(error); } } ``` 這基於 Promise,例如 `doSomething()` 和之前一樣。你可以閱讀在這裡閱讀更多。 Promise 藉由捕捉所有錯誤,包含例外和程式錯誤,解決了 Callback 地獄的缺點。這是非同步運算的基本特性。 在舊有 API 上建立 Promise ------------------- `Promise` 可以透過建構子建立。所以用建構子包裹舊的 API 即可。 在理想情況,所有非同步函數都會回傳 Promise,然而許多 API 仍然用舊的方式來傳遞成功、失敗 Callback,有個典型的例子是`setTimeout()` (en-US) : ```js setTimeout(() => saySomething("10 seconds passed"), 10000); ``` 混合古代 Callback 和 Promise 是有問題的。如果 `saySomething` 失敗或有程式錯誤,那不會有任何錯誤被捕捉。 幸運地,我們可以用 Promise 包裹他,最好盡可能的在最底層包裹,並永遠不要再直接呼叫他們: ```js const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); wait(10000) .then(() => saySomething("10 seconds")) .catch(failureCallback); ``` 基本上,Promise 建構子需要一個運作函數來正規地處理或拒絕 Promise。但因為 `setTimeout` 不會失敗,所以我們捨棄 reject。 組合 -- `Promise.resolve()` 和 `Promise.reject()` 是用來正規地建立已經處理或拒絕的 Promise。他們在某些情況特別有用。 `Promise.all()` 和 `Promise.race()` 是兩個組合工具用於使 Promise 平行運作。 連續關聯是可行的,這是極簡 JavaScript 範例: ```js [func1, func2].reduce((p, f) => p.then(f), Promise.resolve()); ``` 基本上,我們摺疊(Reduce)一個非同步函數陣列成一個 Promise 鏈:`Promise.resolve().then(func1).then(func2);` 這可以用可重用的構成函數完成,通常用函數式編程: ```js let applyAsync = (acc, val) => acc.then(val); let composeAsync = (...funcs) => (x) => funcs.reduce(applyAsync, Promise.resolve(x)); ``` `composeAsync` 接受任何數量的函數作為參數,並回傳一個接受一個初始值用來傳給組合的新函數。這個好處是無論其中函數是非同步或否,都會保證用正確的順序執行: ```js let transformData = composeAsync(func1, asyncFunc1, asyncFunc2, func2); transformData(data); ``` ECMAScript 2017 中連續組合利用 async/await 更簡單: ```js for (let f of [func1, func2]) { await f(); } ``` 計時 -- 為了避免意外,傳給 `then` 的函數不會被同步地呼叫,即使是完成的 Promise: ```js Promise.resolve().then(() => console.log(2)); console.log(1); // 1, 2 ``` 被傳入的函數會被放在子任務佇列而非立即執行,因此他會在當前的事件迴圈結束、佇列清空時執行,例如: ```js const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); wait().then(() => console.log(4)); Promise.resolve() .then(() => console.log(2)) .then(() => console.log(3)); console.log(1); // 1, 2, 3, 4 ``` 看更多 --- * `Promise.then()` * Promises/A+ 特色 * Venkatraman.R - JS Promise (Part 1, Basics) * Venkatraman.R - JS Promise (Part 2 - Using Q.js, When.js and RSVP.js) * Venkatraman.R - Tools for Promises Unit Testing * Nolan Lawson: We have a problem with promises — Common mistakes with promises
正規表達式 - JavaScript
正規表達式 ===== * « 前頁 (en-US) * 次頁 » (en-US) 正規表達式是被用來匹配字串中字元組合的模式。在 JavaScript 中,正規表達式也是物件,這些模式在 `RegExp` (en-US) 的 `exec` (en-US) 和 `test` (en-US) 方法中,以及 `String` 的 `match` (en-US)、`replace` (en-US)、`search` (en-US)、`split` (en-US) 等方法中被運用。這一章節將解說 JavaScript 中的正規表達式。 建立正規表達式 ------- 你可透過下列兩種方法去創建一條正規表達式: 使用正規表達式字面值(regular expression literal),包含兩個 `/` 字元之間的模式如下: ```js var re = /ab+c/; ``` 正規表達式字面值在 script 載入時會被編譯,當正規表達式為定值時,使用此方法可獲得較佳效能。 或呼叫 `RegExp` (en-US) 物件的建構函式,如下: ```js var re = new RegExp("ab+c"); ``` 使用建構子函數供即時編譯正則表達式,當模式會異動、事先未知匹配模式、或者你將從其他地方取得時,使用建構子函數將較為合適。 撰寫正規表達模式 -------- 正規表達模式由數個簡易字元組成,例如 `/abc/`,或是由簡易字元及特殊符號組合而成,例如 `/ab*c/`、`/Chapter (\d+)\.\d*/ )`。最後一個範例用到了括號,這在正規表達式中用作記憶組,使用括號的匹配將會被留到後面使用,在使用帶括號的配對子字串有更多解釋。 ### 使用簡易模式 簡易的模式是有你找到的直接匹配所構成的。比如:`/abc/` 這個模式就匹配了在一個字符串中,僅僅字符 `'abc'` 同時出現並按照這個順序。這兩個句子中「*Hi, do you know your abc's?*」和「*The latest airplane designs evolved from slabcraft.*」就會匹配成功。在上面的兩個實例中,匹配的是子字符串 'abc'。在字符串中的 "Grab crab"('ab c') 中將不會被匹配,因為它不包含任何的 'abc' 字符串。 ### 使用特殊字元 當你需要搜尋一個比直接匹配需要更多條件的匹配,比如搜尋一或多個 'b',或者搜尋空格,那麼這個模式將要包含特殊字符。例如: 模式 `/ab*c/` 匹配了一個單獨的 'a' 後面跟了零或多個 'b'(\* 的意思是前面一項出現了零或多個),且後面跟著 'c' 的任何字符組合。在字符串 "cbbabbbbcdebc" 中,這個模式匹配了子字符串 "abbbbc"。 下面的表格列出了在正則表達式中可以利用的特殊字符完整列表以及描述。 | 字元 | 解說 | | --- | --- | | `\` | 反斜線放在非特殊符號前面,使非特殊符號不會被逐字譯出,代表特殊作用。 例如:'b' 如果沒有 '\' 在前頭,功能是找出小寫 b;若改為 '\b' 則代表的是邊界功能,block 用意。 /\bter\b/.test("interest") //false /\bter\b/.test("in ter est") //true `/a*/` 找出 0 個或是 1 個以上的 a;而 /a\\*/ 找出 'a\*' 這個字串 /aaaa\*/g.test("caaady") //true /a\\*/.test("caaady") //false '\' 也能使自身表現出來,表現 '\' ,必須以 '\\' 表達。 /[\\]/.test(">\\<") //true | | `^` | 匹配輸入的開頭,如果 multiline flag 被設為 true,則會匹配換行字元後。例如:`/^A/` 不會匹配「an A」的 A,但會匹配「An E」中的 A。「`^`」出現在字元集模式的字首中有不同的意思,詳見補字元集。 | | `$` | 匹配輸入的結尾,如果 multiline flag 被設為 true,則會匹配換行字元。例如:`/t$/` 不會匹配「eater」中的 t,卻會匹配「eat」中的 t。 | | `*` | 匹配前一字元 0 至多次。 下面舉例要求基本 'aaaa' ,'a\*' 後面有 0 個或多個 a 的意思 /aaaaa\*/g.test("caaady") //false 例如:`/bo*/` 匹配「A ghost booooed」中的 boooo、「A bird warbled」中的 b,但在「A goat grunted」中不會匹配任何字串。 | | `+` | 匹配前一字元 1 至多次,等同於 `{1,}`。例如:`/a+/` 匹配「candy」中的 a,以及所有「caaaaaaandy」中的 a。 | | `?` | 匹配前一字元 0 至 1 次,等同於 `{0,1}`。例如:`/e?le?/` 匹配「angel」中的 el、「angle」中的 le、以及「oslo」中的 l。如果是使用在 `*`、`+`、`?` 或 `{}` 等 quantifier 之後,將會使這些 quantifier non-greedy(也就是儘可能匹配最少的字元),與此相對的是 greedy(匹配儘可能多的字元)。例如:在「123abc」中應用 `/\d+/` 可匹配「123」,但使用 `/\d+?/` 在相同字串上只能匹配「1」。 Also used in lookahead assertions, as described in the `x(?=y)` and `x(?!y)` entries of this table. | | `.` | (小數點)匹配除了換行符號之外的單一字元。例如:/.n/ 匹配「nay, an apple is on the tree」中的 an 和 on,但在「nay」中沒有匹配。 | | `(x)` | Capturing Parentheses 匹配 'x' 並記住此次的匹配,如下面的範例所示。在 正則表達示 /(foo) (bar) \1 \2/ 中的 (foo) 與 (bar) 可匹配了 "foo bar foo bar" 這段文字中的前兩個字,而 \1 與 \2 則匹配了後面的兩個字。注意, \1, \2, ..., \n 代表的就是前面的 pattern,以本範例來說,/(foo) (bar) \1 \2/ 等同於 /(foo) (bar) (foo) (bar)/。用於取代(replace)的話,則是用 $1, $2,...,$n。如 'bar boo'.replace(/(...) (...)/, '$2 $1'). `$&` 表示已匹配的字串 | | `(?:x)` | *Non-Capturing Parentheses*找出 'x',這動作不會記憶 `()`為 group 的意思,檢查時會再 wrap 一次,若有 `g` flag 會無效, `?:` 代表只要 group 就好,不要 wrap 有無 `()` 差別 ? `'foo'.match(/(foo)/)` `// ['foo', 'foo', index: 0, input: 'foo' ] 'foo'.match(/foo/) // [ 'foo', index: 0, input: 'foo' ]`有無`?:`差別? `'foo'.match(/(foo){1,2}/) // [ 'foo', 'foo', index: 0, input: 'foo' ] 'foo'.match(/(?:foo){1,2}/) [ 'foo', index: 0, input: 'foo' ]` 連`()`都沒有,則`{1,2}`只是適用在`foo`的第二個`o`的條件而已。更多資訊詳見 Using parentheses 。 | | `x(?=y)` | 符合'x',且後接的是'y'。'y'為'x'存在的意義。 例如:`/Jack(?=Sprat)/,`在後面是 Sprat 的存在下,Jack 才有意義。 `/Jack(?=Sprat|Frost)/`後面是 Sprat「或者是」Frost 的存在下,Jack 才有意義。但我們要找的目標是 Jack,後面的條件都只是 filter/條件的功能而已。 | | `x(?!y)` | 符合'x',且後接的不是'y'。'y'為否定'x'存在的意義,後面不行前功盡棄(negated lookahead)。 例如: `/\d+(?!\.)/` ,要找一個或多個數字時,在後面接的不是「點」的情況下成立。 `var result = /\d+(?!\.)/.exec("3.141")` , result 執行出來為[ '141', index: 2, input: '3.141'], index:2,代表 141 從 index = 2 開始。 | | `x|y` | 符合「x」或「y」。舉例來說,`/green|red/` 的話,會匹配 `"green apple"` 中的 `"green"` 以及 `"red apple."` 的 `"red"` 。 | | `{n}` | 規定符號確切發生的次數,n 為正整數例如:`/a{2}/`無法在 "candy" 找到、但 "caandy" 行;若字串擁有 2 個以上 "caaandy" 還是只會認前面 2 個。 | | `{n,m}` | 搜尋條件:n 為至少、m 為至多,其 n、m 皆為正整數。若把 m 設定為 0,則為 Invalid regular expression。例如:`/a{1,3}/`無法在 "cndy" 匹配到;而在 "candy" 中的第 1 個"a"符合;在 "caaaaaaandy" 中的前 3 個 "aaa" 符合,雖然此串有許多 a,但只認前面 3 個。 | | `[xyz]` | 字元的集合。此格式會匹配中括號內所有字元, including escape sequences。特殊字元,例如點(`.`) 和米字號(`*`),在字元集合中不具特殊意義,所以不需轉換。若要設一個字元範圍的集合,可以使用橫線 `"-"` ,如下例所示: `[a-d]` 等同於 `[abcd]。`會匹配 "brisket" 的 "b" 、"city" 的 'c' ……等。 而`/[a-z.]+/` 和 `/[\w.]+/` 均可匹配字串 "test.i.ng" 。 | | `[^xyz]` | bracket 中寫入的字元將被否定,匹配非出現在 bracket 中的符號。 可用 '-' 來界定字元的範圍。一般直接表達的符號都可以使用這種方式。`[^abc]`可以寫作[^`a-c]`. "brisket" 中找到 'r' 、"chop."中找到 'h'。 | | `[\b]` | 吻合倒退字元 (U+0008). (不會跟 \b 混淆) | | `\b` | 吻合文字邊界。A word boundary matches the position where a word character is not followed or preceded by another word-character. Note that a matched word boundary is not included in the match. In other words, the length of a matched word boundary is zero. (Not to be confused with `[\b]`.)Examples: `/\bm/` matches the 'm' in "moon" ; `/oo\b/` does not match the 'oo' in "moon", because 'oo' is followed by 'n' which is a word character; `/oon\b/` matches the 'oon' in "moon", because 'oon' is the end of the string, thus not followed by a word character; `/\w\b\w/` will never match anything, because a word character can never be followed by both a non-word and a word character.**Note:** JavaScript's regular expression engine defines a specific set of characters to be "word" characters. Any character not in that set is considered a word break. This set of characters is fairly limited: it consists solely of the Roman alphabet in both upper- and lower-case, decimal digits, and the underscore character. Accented characters, such as "é" or "ü" are, unfortunately, treated as word breaks. | | `\B` | 吻合非文字邊界。This matches a position where the previous and next character are of the same type: Either both must be words, or both must be non-words. The beginning and end of a string are considered non-words.For example, `/\B../` matches 'oo' in "noonday", and `/y\B./` matches 'ye' in "possibly yesterday." | | `\cX` | Where *X* is a character ranging from A to Z. Matches a control character in a string.For example, `/\cM/` matches control-M (U+000D) in a string. | | `\d` | 吻合數字,寫法等同於 `[0-9] 。`例如:`/\d/` 或 `/[0-9]/` 在 "B2 is the suite number." 中找到 '2' | | `\D` | 吻合非數字,寫法等同於 `[^0-9]。`例如:`/\D/` 或`/[^0-9]/` 在 "B2 is the suite number." 中找到 'B' 。 | | `\f` | Matches a form feed (U+000C). | | `\n` | Matches a line feed (U+000A). | | `\r` | Matches a carriage return (U+000D). | | `\s` | Matches a single white space character, including space, tab, form feed, line feed. Equivalent to `[ \f\n\r\t\v\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]`.For example, `/\s\w*/` matches ' bar' in "foo bar." | | `\S` | Matches a single character other than white space. Equivalent to `[^ \f\n\r\t\v\u00a0\\u1680u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]`.For example, `/\S\w*/` matches 'foo' in "foo bar." | | `\t` | Matches a tab (U+0009). | | `\v` | Matches a vertical tab (U+000B). | | `\w` | 包含數字字母與底線,等同於`[A-Za-z0-9_]`。例如: `/\w/` 符合 'apple'中的 'a' 、'$5.28 中的 '5' 以及 '3D' 中的 '3'。For example, `/\w/` matches 'a' in "apple," '5' in "$5.28," and '3' in "3D." | | `\W` | 包含"非"數字字母與底線,等同於`[^A-Za-z0-9_]`。例如: `/\W/` 或是 `/[^A-Za-z0-9_]/` 符合 "50%." 中的 '%'For example, `/\W/` or `/[^A-Za-z0-9_]/` matches '%' in "50%." | | `\n` | 其中 *n* 是一個正整數,表示第 *n* 個括號中的子字串匹配(包含括號中的所有的字串匹配)例如: `/apple(,)\sorange\1/` 符合 "apple, orange, cherry, peach." 的 'apple, orange,' 。( `\1` 表示第一個 partten ,也就是 `(,)`)For example, `/apple(,)\sorange\1/` matches 'apple, orange,' in "apple, orange, cherry, peach." | | `\0` | Matches a NULL (U+0000) character. Do not follow this with another digit, because `\0<digits>` is an octal escape sequence. Instead use `\x00`. | | `\xhh` | Matches the character with the code hh (two hexadecimal digits) | | `\uhhhh` | Matches the character with the code hhhh (four hexadecimal digits). | Escaping user input that is to be treated as a literal string within a regular expression—that would otherwise be mistaken for a special character—can be accomplished by simple replacement: ```js function escapeRegExp(string) { return string.replace(/[.\*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string } ``` The g after the regular expression is an option or flag that performs a global search, looking in the whole string and returning all matches. It is explained in detail below in Advanced Searching With Flags. ### 使用括號 Parentheses around any part of the regular expression pattern causes that part of the matched substring to be remembered. Once remembered, the substring can be recalled for other use, as described in Using Parenthesized Substring Matches. For example, the pattern `/Chapter (\d+)\.\d*/` illustrates additional escaped and special characters and indicates that part of the pattern should be remembered. It matches precisely the characters 'Chapter ' followed by one or more numeric characters (`\d` means any numeric character and `+` means 1 or more times), followed by a decimal point (which in itself is a special character; preceding the decimal point with \ means the pattern must look for the literal character '.'), followed by any numeric character 0 or more times (`\d` means numeric character, `*` means 0 or more times). In addition, parentheses are used to remember the first matched numeric characters. This pattern is found in "Open Chapter 4.3, paragraph 6" and '4' is remembered. The pattern is not found in "Chapter 3 and 4", because that string does not have a period after the '3'. To match a substring without causing the matched part to be remembered, within the parentheses preface the pattern with `?:`. For example, `(?:\d+)` matches one or more numeric characters but does not remember the matched characters. 運用正規表達式 ------- Regular expressions are used with the `RegExp` methods `test` and `exec` and with the `String` methods `match`, `replace`, `search`, and `split`. These methods are explained in detail in the JavaScript reference. | Method | Description | | --- | --- | | `exec` (en-US) | A `RegExp` method that executes a search for a match in a string. It returns an array of information or null on a mismatch. | | `test` (en-US) | A `RegExp` method that tests for a match in a string. It returns true or false. | | `match` (en-US) | A `String` method that executes a search for a match in a string. It returns an array of information or null on a mismatch. | | `search` (en-US) | A `String` method that tests for a match in a string. It returns the index of the match, or -1 if the search fails. | | `replace` (en-US) | A `String` method that executes a search for a match in a string, and replaces the matched substring with a replacement substring. | | `split` (en-US) | A `String` method that uses a regular expression or a fixed string to break a string into an array of substrings. | When you want to know whether a pattern is found in a string, use the `test` or `search` method; for more information (but slower execution) use the `exec` or `match` methods. If you use `exec` or `match` and if the match succeeds, these methods return an array and update properties of the associated regular expression object and also of the predefined regular expression object, `RegExp`. If the match fails, the `exec` method returns `null` (which coerces to `false`). In the following example, the script uses the `exec` method to find a match in a string. ```js var myRe = /d(b+)d/g; var myArray = myRe.exec("cdbbdbsbz"); ``` If you do not need to access the properties of the regular expression, an alternative way of creating `myArray` is with this script: ```js var myArray = /d(b+)d/g.exec("cdbbdbsbz"); // similar to "cdbbdbsbz".match(/d(b+)d/g); however, // the latter outputs Array [ "dbbd" ], while // /d(b+)d/g.exec('cdbbdbsbz') outputs Array [ "dbbd", "bb" ]. // See below for further info (CTRL+F "The behavior associated with the".) ``` If you want to construct the regular expression from a string, yet another alternative is this script: ```js var myRe = new RegExp("d(b+)d", "g"); var myArray = myRe.exec("cdbbdbsbz"); ``` With these scripts, the match succeeds and returns the array and updates the properties shown in the following table. Results of regular expression execution.| 物件 | Property or index | 說明 | 範例 | | --- | --- | --- | --- | | `myArray` | | The matched string and all remembered substrings. | `['dbbd', 'bb', index: 1, input: 'cdbbdbsbz']` | | `index` | The 0-based index of the match in the input string. | `1` | | `input` | The original string. | `"cdbbdbsbz"` | | `[0]` | The last matched characters. | `"dbbd"` | | `myRe` | `lastIndex` | The index at which to start the next match. (This property is set only if the regular expression uses the g option, described in Advanced Searching With Flags.) | `5` | | `source` | The text of the pattern. Updated at the time that the regular expression is created, not executed. | `"d(b+)d"` | As shown in the second form of this example, you can use a regular expression created with an object initializer without assigning it to a variable. If you do, however, every occurrence is a new regular expression. For this reason, if you use this form without assigning it to a variable, you cannot subsequently access the properties of that regular expression. For example, assume you have this script: ```js var myRe = /d(b+)d/g; var myArray = myRe.exec("cdbbdbsbz"); console.log("The value of lastIndex is " + myRe.lastIndex); // "The value of lastIndex is 5" ``` However, if you have this script: ```js var myArray = /d(b+)d/g.exec("cdbbdbsbz"); console.log("The value of lastIndex is " + /d(b+)d/g.lastIndex); // "The value of lastIndex is 0" ``` The occurrences of `/d(b+)d/g` in the two statements are different regular expression objects and hence have different values for their `lastIndex` property. If you need to access the properties of a regular expression created with an object initializer, you should first assign it to a variable. ### Using Parenthesized Substring Matches Including parentheses in a regular expression pattern causes the corresponding submatch to be remembered. For example, `/a(b)c/` matches the characters 'abc' and remembers 'b'. To recall these parenthesized substring matches, use the `Array` elements `[1]`, ..., `[n]`. The number of possible parenthesized substrings is unlimited. The returned array holds all that were found. The following examples illustrate how to use parenthesized substring matches. 下面這個 script 以 `replace()` (en-US) 方法移轉字串位置。對於要被置換的文字內容,以 `$1` 和 `$2` 來代表先前 re 這個變數裡面,找出來綑綁且照順序來表示兩個子字串。 ```js var re = /(\w+)\s(\w+)/; var str = "John Smith"; var newstr = str.replace(re, "$2, $1"); console.log(newstr); // "Smith, John" ``` ### Advanced Searching With Flags Regular expressions have five optional flags that allow for global and case insensitive searching. These flags can be used separately or together in any order, and are included as part of the regular expression. | Flag | Description | | --- | --- | | `g` | Global search. | | i | Case-insensitive search. | | m | Multi-line search. | | u | unicode; treat a pattern as a sequence of unicode code points | | y | Perform a "sticky" search that matches starting at the current position in the target string. See `sticky` (en-US) | To include a flag with the regular expression, use this syntax: ```js var re = /pattern/flags; ``` or ```js var re = new RegExp("pattern", "flags"); ``` Note that the flags are an integral part of a regular expression. They cannot be added or removed later. For example, `re = /\w+\s/g` creates a regular expression that looks for one or more characters followed by a space, and it looks for this combination throughout the string. ```js var re = /\w+\s/g; var str = "fee fi fo fum"; var myArray = str.match(re); console.log(myArray); // ["fee ", "fi ", "fo "] ``` You could replace the line: ```js var re = /\w+\s/g; ``` with: ```js var re = new RegExp("\\w+\\s", "g"); ``` and get the same result. The behavior associated with the '**`g`**' flag is different when the `.exec()` method is used. (The roles of "class" and "argument" get reversed: In the case of `.match()`, the string class (or data type) owns the method and the regular expression is just an argument, while in the case of `.exec()`, it is the regular expression that owns the method, with the string being the argument. Contrast *`str.match(re)`* versus *`re.exec(str)`*.) The '**`g`**' flag is used with the **`.exec()`** method to get iterative progression. ```js var xArray; while ((xArray = re.exec(str))) console.log(xArray); // produces: // ["fee ", index: 0, input: "fee fi fo fum"] // ["fi ", index: 4, input: "fee fi fo fum"] // ["fo ", index: 7, input: "fee fi fo fum"] ``` The `m` flag is used to specify that a multiline input string should be treated as multiple lines. If the `m` flag is used, `^` and `$` match at the start or end of any line within the input string instead of the start or end of the entire string. 範例 -- The following examples show some uses of regular expressions. ### Changing the order in an input string The following example illustrates the formation of regular expressions and the use of `string.split()` and `string.replace()`. It cleans a roughly formatted input string containing names (first name last) separated by blanks, tabs and exactly one semicolon. Finally, it reverses the name order (last name first) and sorts the list. ```js // The name string contains multiple spaces and tabs, // and may have multiple spaces between first and last names. var names = "Orange Trump ;Fred Barney; Helen Rigby ; Bill Abel ; Chris Hand "; var output = ["---------- Original String\n", names + "\n"]; // Prepare two regular expression patterns and array storage. // Split the string into array elements. // pattern: possible white space then semicolon then possible white space var pattern = /\s\*;\s\*/; // Break the string into pieces separated by the pattern above and // store the pieces in an array called nameList var nameList = names.split(pattern); // new pattern: one or more characters then spaces then characters. // Use parentheses to "memorize" portions of the pattern. // The memorized portions are referred to later. pattern = /(\w+)\s+(\w+)/; // Below is the new array for holding names being processed. var bySurnameList = []; // Display the name array and populate the new array // with comma-separated names, last first. // // The replace method removes anything matching the pattern // and replaces it with the memorized string—the second memorized portion // followed by a comma, a space and the first memorized portion. // // The variables $1 and $2 refer to the portions // memorized while matching the pattern. output.push("---------- After Split by Regular Expression"); var i, len; for (i = 0, len = nameList.length; i < len; i++) { output.push(nameList[i]); bySurnameList[i] = nameList[i].replace(pattern, "$2, $1"); } // Display the new array. output.push("---------- Names Reversed"); for (i = 0, len = bySurnameList.length; i < len; i++) { output.push(bySurnameList[i]); } // Sort by last name, then display the sorted array. bySurnameList.sort(); output.push("---------- Sorted"); for (i = 0, len = bySurnameList.length; i < len; i++) { output.push(bySurnameList[i]); } output.push("---------- End"); console.log(output.join("\n")); ``` ### 使用特殊字元驗證輸入 In the following example, the user is expected to enter a phone number. When the user presses the "Check" button, the script checks the validity of the number. If the number is valid (matches the character sequence specified by the regular expression), the script shows a message thanking the user and confirming the number. If the number is invalid, the script informs the user that the phone number is not valid. Within non-capturing parentheses `(?:` , the regular expression looks for three numeric characters `\d{3}` OR `|` a left parenthesis `\(` followed by three digits `\d{3}`, followed by a close parenthesis `\)`, (end non-capturing parenthesis `)`), followed by one dash, forward slash, or decimal point and when found, remember the character `([-\/\.])`, followed by three digits `\d{3}`, followed by the remembered match of a dash, forward slash, or decimal point `\1`, followed by four digits `\d{4}`. The `Change` event activated when the user presses Enter sets the value of `RegExp.input`. ```html <!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> <meta http-equiv="Content-Script-Type" content="text/javascript" /> <script type="text/javascript"> var re = /(?:\d{3}|\(\d{3}\))([-\/\.])\d{3}\1\d{4}/; function testInfo(phoneInput) { var OK = re.exec(phoneInput.value); if (!OK) window.alert( phoneInput.value + " isn't a phone number with area code!", ); else window.alert("Thanks, your phone number is " + OK[0]); } </script> </head> <body> <p> Enter your phone number (with area code) and then click "Check". <br />The expected format is like ###-###-####. </p> <form action="#"> <input id="phone" /><button onclick="testInfo(document.getElementById('phone'));"> Check </button> </form> </body> </html> ``` * « 前頁 (en-US) * 次頁 » (en-US)
語法與型別 - JavaScript
語法與型別 ===== * « 前頁 * 次頁 » 本章討論 JavaScript 的基本語法與基礎資料類型、包括變數、常數、字元常數 基礎知識 ---- JavaScript 許多基本語法借鑒自 Java,C 或是 C++,但亦受 Awk、Perl 和 Python 的影響。 JavaScript 是 Case-sensitive(區分大小寫)並使用 Unicode 編碼。舉例來說,Früh (德文的"early") 可以當作變數的名稱。 ``` var Früh = "foobar"; ``` 但變數 früh 並不等於 Früh,因為大小寫對 JavaScript 是有區別的。 在 JavaScript 中,每行指令被稱為 Statements (en-US),並用分號(;)分隔。空格、Tab 與換行符號皆被視為空白。JavaScript 的文件會從左到右進行掃描,並轉換成一系列的元素,像是令牌(Token)、控制字符(Control characters)、換行器(line terminators)、註解(Comments)或是空白(Withespace),ECMAScript 也定義了特定的保留字和字面值,並在每個沒有加分號的 Statement 自動加上分號。然而,推薦的作法還是在每個 Statement 的結尾自行加上分號,以防止一些潛在的副作用,如果需要更多資訊,可以參考這篇。 註解(Comments) ------------ 註解語法跟 C++ 和其他語言相同: ```js // a one line comment /\* this is a longer, multi-line comment \*/ /\* You can't, however, /\* nest comments \*/ SyntaxError \*/ ``` 宣告(Declarations) ---------------- JavaScript 有三種宣告方式 `var` 宣告一個可隨意更改其內容的變數 `let` 宣告一個可隨意更改其內容的區塊區域變數 `const` 宣告一個只可讀取的不可變常數 ### 變數(Variables) 變數(variable)是對值(value)的引用,變數的名稱被稱為 identifiers 需要遵從一定的規則。 在 JavaScript 中,變數必須使用字母(letter)、下底線(\_)、錢號($)作為開頭;後面的字員組成可以包含數字(0-9)。JavaScript 是區分大小寫(case sensitive)的,大寫字母('A' ~ 'Z')和小寫字母('a' ~ 'z')皆可使用且不相等。 You can use most of ISO 8859-1 or Unicode letters such as å and ü in identifiers (for more details see this blog post). You can also use the Unicode escape sequences as characters in identifiers. Some examples of legal names are `Number_hits`, `temp99`, `$credit`, and `_name`. ### 定義變數 你可以透過三種方式來定義變數: * 透過保留字 `var` 來定義變數,舉例來說: `var x = 42`,這種方式可以用來定義區域以及全域變數。 * 直接指定一個值給該變數,例如:`x = 42`,這種方式只能定義全域變數,如果在方法外面使用該方法定義變數,嚴格模式裡會產生警告,該定義方式應該盡可能避免。 * 透過保留字 `let`,舉例來說:`let y = 13`,`let` 可以用來定義區塊裡的區域變數。想瞭解更多,可以參考變數區域的章節。 ### 變數取值 變數可以透過 `var` 或是 `let` 來定義,如果尚未指定數值給該變數,那麼該變數的值會是 `undefined` (en-US)。如果嘗試去存取未定義的變數,會跳出 `ReferenceError` (en-US) 的例外。 ```js var a; console.log("The value of a is " + a); // The value of a is undefined console.log("The value of b is " + b); // The value of b is undefined var b; console.log("The value of c is " + c); // Uncaught ReferenceError: c is not defined let x; console.log("The value of x is " + x); // The value of x is undefined console.log("The value of y is " + y); // Uncaught ReferenceError: y is not defined let y; ``` 你可以利用 `undefined` 來判斷該變數是否有值,在下面的程式碼的例子中,`input` 這個變數沒有賦值,`if` 判斷式會得到 `true` 的結果。 ```js var input; if (input === undefined) { doThis(); } else { doThat(); } ``` 被賦予 `undefined` 的變數,在被當做布林值的情境下都會被視為 `false`,以下面的例子來說,程式碼會執行 `myFunction`,因為 `myArray` 是 `undefined`: ```js var myArray = []; if (!myArray[0]) myFunction(); ``` 被賦予 `undefined` 的變數,在和數值進行運算之後,會被轉成非數值(`NaN`): ```js var a; a + 2; // Evaluates to NaN ``` 當你對 `null` (en-US) 進行運算,`null` (en-US) 會自動轉換成數值 0,如果當做布林值運算,會被當成 `false`,舉例來說: ```js var n = null; console.log(n \* 32); // Will log 0 to the console ``` ### 變數範圍 當我們在函式外宣告一個變數時,這個變數會是一個全域變數 (global variable), 因為在這份程式文件裡面的所有程式碼都可以使用到這個變數。但當我們只在函式內宣告變數時,這變數是區域變數 (local variable),因為變數只會在函式內被使用到。 **請注意!!** 在 ECMAScript 2015 以前的 JavaScript 版本裡,並沒有定義區塊描述 (block statement) 的變數有效範圍。更精確的說,之前版本所定義的變數,其特性相當於全域變數;不只在宣告的區塊或函數裡面有效 ,其變數值還會超出宣告區塊而影響到全部的描述碼。 從下面例子來看,其輸出結果會是 5。雖然 x 是在 if { } 區塊裡面被宣告的,但卻因為有全域變數的特性,因此溢出大括號而成為後續描述碼的變數值。 ```js if (true) { var x = 5; } console.log(x); // x is 5 ``` 接著舉一個 ECMAScript 2015 之後的宣告範例。當使用了 `let` 這個區域變數宣告方式,變數 y 的有效範圍只有在 if { } 的範圍內,因此輸出結果是 ReferenceError。 ```js if (true) { let y = 5; } console.log(y); // ReferenceError: y is not defined (y沒有被定義) ``` ### 變數提升 在 JavaScript 中另一件有關變數不常見的事, 是你可引用一個較晚宣告的變數並且不會有異常。這個概念被稱為「**提升**(**hoisting**)」;從意義上來說明,變數在 JavaScript 中是「被提升(hoisted)」或「被抬至(lifted)」到函式(function)或陳述式(statement)的頂部。 然而,被提升(hoisted)的變數將返回一個未定義的值(undefined)。所以即使你在使用或者引用這個變數之後才宣告和初始化它,它仍然會返回它是一個未定義的值(undefined)。 ```js /\*\* \* Example 1 \*/ console.log(x === undefined); // true var x = 3; /\*\* \* Example 2 \*/ // will return a value of undefined var myvar = "my value"; (function () { console.log(myvar); // undefined var myvar = "local value"; })(); ``` 上面的例子可以轉譯成如下相同的程式: ```js /\*\* \* Example 1 \*/ var x; console.log(x === undefined); // true x = 3; /\*\* \* Example 2 \*/ var myvar = "my value"; (function () { var myvar; console.log(myvar); // undefined myvar = "local value"; })(); ``` 由於提升(hoisting),全部在函數(function) 中的 var 陳述式應該盡可能地置放在接近函數(function)的頂部。這個最佳實踐增加了程式碼的清晰度。 在 ECMAScript 2015 中,let(const)不會將變數提升到區塊(block)的頂部。但是,在變數宣告之前就引用塊中的變數,會導致 `ReferenceError` (en-US)。變數從區塊(block)的開始到宣告被處理之前,就處於「暫時無效(temporal dead zone)」。 ```js console.log(x); // ReferenceError let x = 3; ``` ### 函式提升 針對函式來說,只有函式宣告式(function declaration)提昇到頂部,但函式表示式(function exprssion) 不被提昇至頂部。 ```js /\* Function declaration \*/ foo(); // "bar" function foo() { console.log("bar"); } /\* Function expression \*/ baz(); // TypeError: baz is not a function var baz = function () { console.log("bar2"); }; ``` ### 全域變數 (Global variables) 全域變數事實上是全域物件的屬性值。在網頁中的全域物件是 `window` (en-US),因此你可使用 `window.variable` 的語法來設定及存取全域變數。 Consequently, 你可以指定 window 或 frame 物件的名稱來存取在另一個在 window 物件或 frame 物件所宣告的全域變數。例如,如果在一個文檔中已宣告一個稱為 `phoneNumber` 的變數,你可以在 iframe 中使用 `parent.phoneNumber` 來存取該變數 ### 常數 (Constants) 你可用 `const` 關鍵字來建立一個唯讀、有名稱的常數。 常數識別子的命名語法與變數識別子的命名語法是一樣的: 必須由一個英文字母,底線或錢符號($)開始,之後可包含英文字母,數字及底線字元。 ```js const PI = 3.14; ``` 當程式執行時,無法再透過賦值或重新宣告來改變常數已設定的值。常數必須被初始化。 The scope rules for constants are the same as those for `let` block-scope variables. If the `const` keyword is omitted, the identifier is assumed to represent a variable. 你不能在同一個局部範圍內使用與其它函式或變數相同的名稱來宣告變數。例如: ```js // THIS WILL CAUSE AN ERROR function f() {} const f = 5; // THIS WILL CAUSE AN ERROR ALSO function f() { const g = 5; var g; //statements } ``` 但是常數物件內的物件屬性並不受到保護,因此以下陳述式可以正常執行。 ```js const MY\_OBJECT = { key: "value" }; MY\_OBJECT.key = "otherValue"; ``` 資料結構及型別 ------- ### 資料型別 (Data types) 最新 ECMAScript 標準定義以下七種資料型別: * 六種基本(primitives (en-US))資料型別 : + Boolean. `true` and `false`. + null. A special keyword denoting a null value. Because JavaScript is case-sensitive, `null` is not the same as `Null`, `NULL`, or any other variant. + undefined (en-US). A top-level property whose value is undefined. + Number. `42` or `3.14159`. + String (en-US). "Howdy" + Symbol (en-US) (new in ECMAScript 2015). A data type whose instances are unique and immutable. * and Object 儘管這些變數關聯性很小,他們可以讓你在你的應用程式中,產生出有意義的函數。 物件 (en-US)與 函數 (en-US) 在語言中是其它的基本元素. 你可以把物件想成是一個被命名過且用來裝數值的容器,以及函數則為你的應用程式所執行的步驟. ### 資料型別轉換 JavaScript 是一個動態型別的語言,這意味著你不需要在宣告變數時定義它的資料型別,程式執行時會自動轉換,你可以用下面方式宣告變數: ```js var answer = 42; ``` 你可以指派字串在同個變數中,例如: ```js answer = "Thanks for all the fish..."; ``` 由於 Javascript 是一個動態型別的語言,因此這樣的宣告方式不會導致錯誤。 在該陳述式中,它調用了字串和數字,並使用 + 進行運算,JavaScript 會自動把數字轉換成字串,例如: ```js x = "The answer is " + 42; // "The answer is 42" y = 42 + " is the answer"; // "42 is the answer" ``` 在該陳述式中,它調用了其它運算子,JavaScript 就不會將數字轉換成字串,例如: ```js "37" - 7; // 30 "37" + 7; // "377" ``` ### 字串轉數值 當代表數字的值以字串形式存在記憶體中,有些方法可用來將這種字串轉換成整數或浮點數。 * `parseInt()` * `parseFloat()` (en-US) `parseInt` 只會返回整數,因此減少了對小數的使用。此外,parseInt 的最佳實務是始終包含基數參數。基數參數用於指定使用的數值系統。 另一個將字串轉成數字是使用單元 `+` (unary plus) 運算子: ```js '1.1' + '1.1' = '1.11.1' (+'1.1') + (+'1.1') = 2.2 // 注意: 括號是為了易於閱讀,並不是必須的. ``` 字面值(Literals) ------------- 你能使用字面值來表示 JavaScript 中的值。這些是你在腳本中實際提供的固定值,而不是變量。本節描述以下類型的字面值: * Array literals * Boolean literals * Floating-point literals * Integers * Object literals * RegExp literals * String literals ### 陣列字面值 (Array literals) 陣列字面值是零或多個表達式的列表,每個表達式代表一個數組元素,並用方括號([])括起來。使用陣列字面值創建陣列時,將使用指定的值作為其元素對其進行初始化,並將其長度設置為指定的參數值。 以下範例創建了陣列 `coffees` ,長度為 3 並包含三個元素: ```js var coffees = ["French Roast", "Colombian", "Kona"]; ``` **備註:** An array literal is a type of object initializer. See Using Object Initializers (en-US). If an array is created using a literal in a top-level script, JavaScript interprets the array each time it evaluates the expression containing the array literal. In addition, a literal used in a function is created each time the function is called. Array literals are also `Array` objects. See `Array` and Indexed collections (en-US) for details on `Array` objects. #### Extra commas in array literals You do not have to specify all elements in an array literal. If you put two commas in a row, the array is created with `undefined` for the unspecified elements. The following example creates the `fish` array: ```js var fish = ["Lion", , "Angel"]; ``` This array has two elements with values and one empty element (`fish[0]` is "Lion", `fish[1]` is `undefined`, and `fish[2]` is "Angel"). If you include a trailing comma at the end of the list of elements, the comma is ignored. In the following example, the length of the array is three. There is no `myList[3]`. All other commas in the list indicate a new element. **備註:** Trailing commas can create errors in older browser versions and it is a best practice to remove them. ```js var myList = ["home", , "school"]; ``` In the following example, the length of the array is four, and `myList[0]` and `myList[2]` are missing. ```js var myList = [, "home", , "school"]; ``` In the following example, the length of the array is four, and `myList[1]` and `myList[3]` are missing. **Only the last comma is ignored.** ```js var myList = ["home", , "school", ,]; ``` Understanding the behavior of extra commas is important to understanding JavaScript as a language, however when writing your own code: explicitly declaring the missing elements as `undefined` will increase your code's clarity and maintainability. ### 布林字面值 (Boolean literals) 布林型別有兩種字面值: `true` 跟 `false`. Do not confuse the primitive Boolean values `true` and `false` with the true and false values of the Boolean object. The Boolean object is a wrapper around the primitive Boolean data type. See `Boolean` for more information. ### 整數字面值 (Numerical literals) 整數能表示為「十進制」、「十六進制」、「八進制」、「二進制」 * 十進制整數字面值由「『不帶前導 0』的整數序列」組成 * 八進制整數字面值由「『前導 0』」或『前導 0o』或『前導 0O』的整數序列」組成。八進制整數只能包含數字 0-7 * 十六進制整數字面值由「『前導 0x』」或『前導 0X』的整數序列」組成。十六進制整數只能包含數字 0-9 、字母 A-F 和 a-f * 二進制整數字面值由「『前導 0b』」或『前導 0B』的整數序列」組成。二進制整數只能包含數字 0 跟 1 整數字面值範例如下: ``` 0, 117 and -345 (decimal, base 10) 015, 0001 and -0o77 (octal, base 8) 0x1123, 0x00111 and -0xF1A7 (hexadecimal, "hex" or base 16) 0b11, 0b0011 and -0b11 (binary, base 2) ``` 更多資訊請參閱 Numeric literals in the Lexical grammar reference. ### 浮點數字面值 (Floating-point literals) 浮點數字面值能包含以下部分: * 整數部分 (十進位,可帶符號 "+" 或 "-" 於整數前) * 小數點 "." * 小數部分 (另一個十進位整數) * 指數部分 指數部分由「"e" 或 "E" 後面跟整數」所組成,可帶符號 "+" 或 "-" 於整數前。浮點數字面值至少由「一位數字」與「一個小數點 "e" (或 "E")」組成。 簡言之,於法如下: ``` [(+|-)][digits][.digits][(E|e)[(+|-)]digits] ``` 舉個例子: ``` 3.1415926 -.123456789 -3.1E+12 .1e-23 ``` ### 物件字面值 (Object literals) 物件字面值是用大括號({})括起來的零或多對鍵值對的列表。因為 "{" 將被解譯為區塊(block)的開頭,因此你不應在陳述句開頭使用物件字面值,這將導致錯誤或不預期的行為。 以下是物件字面值的範例。`car` 物件包含三個屬性: * 第一個屬性 `myCar` 賦值為字串 '`Saturn`' * 第二個屬性 `getCar` 賦值為「調用函數`carTypes('Honda')`」的結果 * 第三個屬性 `special` 使用現有變量 `sales` 賦值 ```js var sales = "Toyota"; function carTypes(name) { if (name === "Honda") { return name; } else { return "Sorry, we don't sell " + name + "."; } } var car = { myCar: "Saturn", getCar: carTypes("Honda"), special: sales }; console.log(car.myCar); // Saturn console.log(car.getCar); // Honda console.log(car.special); // Toyota ``` 此外,你可以使用數字或字串字面值作為屬性名,也可將物件嵌套在另一個物件中。如下範例: ```js var car = { manyCars: { a: "Saab", b: "Jeep" }, 7: "Mazda" }; console.log(car.manyCars.b); // Jeep console.log(car[7]); // Mazda ``` 物件屬性名可以是任何字串,包括空字串。如果屬性名不是有效的 JavaScript 識別字 或數字,則必須將其用引號引起來。無效的屬性名稱也不能作為點 (`.`) 屬性訪問,但是可以使用類似數組的符號("`[]`")進行訪問和設置。 ```js var unusualPropertyNames = { '': 'An empty string', '!': 'Bang!' } console.log(unusualPropertyNames.''); // SyntaxError: Unexpected string console.log(unusualPropertyNames['']); // An empty string console.log(unusualPropertyNames.!); // SyntaxError: Unexpected token ! console.log(unusualPropertyNames['!']); // Bang! ``` #### Enhanced Object literals In ES2015, object literals are extended to support setting the prototype at construction, shorthand for `foo: foo` assignments, defining methods, making super calls, and computing property names with expressions. Together, these also bring object literals and class declarations closer together, and let object-based design benefit from some of the same conveniences. ```js var obj = { // \_\_proto\_\_ \_\_proto\_\_: theProtoObj, // Shorthand for ‘handler: handler’ handler, // Methods toString() { // Super calls return "d " + super.toString(); }, // Computed (dynamic) property names ["prop\_" + (() => 42)()]: 42, }; ``` Please note: ```js var foo = { a: "alpha", 2: "two" }; console.log(foo.a); // alpha console.log(foo[2]); // two //console.log(foo.2); // Error: missing ) after argument list //console.log(foo[a]); // Error: a is not defined console.log(foo["a"]); // alpha console.log(foo["2"]); // two ``` ### 正規表達式字面值 (RegExp literals) 正則表達式字面值是包含在斜杠間的樣式。以下是正則表達式文字的範例。 ```js var re = /ab+c/; ``` ### 字串字面值 (String literals) 字串字面值是用雙引號(")或單引號(')包住的零或多個字元。字串必須用同類的引號定界;也就是「兩個單引號」或「兩個雙引號」。以下是字串字面值的範例: ```js "foo"; "bar"; "1234"; "one line \n another line"; "John's cat"; ``` 你可以在字串字面值上調用 String 物件的任何方法 - JavaScript 將自動轉換字串字面值為臨時 String 物件並調用該方法,然後丟棄該臨時 String 物件。你還可以將 String.length 屬性與字串字面值一起使用: ```js console.log("John's cat".length); // Will print the number of symbols in the string including whitespace. // In this case, 10. ``` In ES2015, template literals are also available. Template literals are enclosed by the back-tick (` `) (grave accent) character instead of double or single quotes. Template strings provide syntactic sugar for constructing strings. This is similar to string interpolation features in Perl, Python and more. Optionally, a tag can be added to allow the string construction to be customized, avoiding injection attacks or constructing higher level data structures from string contents. ```js // Basic literal string creation `In JavaScript '\n' is a line-feed.` // Multiline strings `In JavaScript template strings can run over multiple lines, but double and single quoted strings cannot.`; // String interpolation var name = "Bob", time = "today"; `Hello ${name}, how are you ${time}?`; // Construct an HTTP request prefix is used to interpret the replacements and construction POST`http://foo.org/bar?a=${a}&b=${b} Content-Type: application/json X-Credentials: ${credentials} { "foo": ${foo}, "bar": ${bar}}`(myOnReadyStateChangeHandler); ``` You should use string literals unless you specifically need to use a String object. See `String` for details on `String` objects. #### 字串裡的特殊字元 除了普通字元,字串也能包含特殊字元,範例如下: ```js "one line \n another line"; ``` 下表列出了可以在 JavaScript 字串中使用的特殊字元。 | 字元 | 意涵 | | --- | --- | | `\0` | Null Byte | | `\b` | 退格 (Backspace) | | `\f` | Form feed | | `\n` | 換行 (New line) | | `\r` | 回車 (Carriage return) | | `\t` | 跳格 (Tab) | | `\v` | Vertical tab | | `\'` | Apostrophe or single quote | | `\"` | Double quote | | `\\` | Backslash character | | `\XXX` | The character with the Latin-1 encoding specified by up to three octal digits *XXX* between 0 and 377. For example, \251 is the octal sequence for the copyright symbol. | | | | | `\xXX` | The character with the Latin-1 encoding specified by the two hexadecimal digits *XX* between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright symbol. | | | | | `\uXXXX` | The Unicode character specified by the four hexadecimal digits *XXXX*. For example, \u00A9 is the Unicode sequence for the copyright symbol. See Unicode escape sequences. | | `\u{XXXXX}` | Unicode code point escapes. For example, \u{2F804} is the same as the simple Unicode escapes \uD87E\uDC04. | #### Escaping characters For characters not listed in the table, a preceding backslash is ignored, but this usage is deprecated and should be avoided. You can insert a quotation mark inside a string by preceding it with a backslash. This is known as *escaping* the quotation mark. For example: ```js var quote = 'He read "The Cremation of Sam McGee" by R.W. Service.'; console.log(quote); ``` The result of this would be: ``` He read "The Cremation of Sam McGee" by R.W. Service. ``` To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path `c:\temp` to a string, use the following: ```js var home = "c:\\temp"; ``` You can also escape line breaks by preceding them with backslash. The backslash and line break are both removed from the value of the string. ```js var str = "this string \ is broken \ across multiple \ lines."; console.log(str); // this string is broken across multiplelines. ``` Although JavaScript does not have "heredoc" syntax, you can get close by adding a line break escape and an escaped line break at the end of each line: ```js var poem = "Roses are red,\n\ Violets are blue.\n\ Sugar is sweet,\n\ and so is foo."; ``` ECMAScript 2015 introduces a new type of literal, namely **template literals** (en-US). This allows for many new features including multiline strings! ```js var poem = `Roses are red, Violets are blue. Sugar is sweet, and so is foo.`; ``` More information ---------------- This chapter focuses on basic syntax for declarations and types. To learn more about JavaScript's language constructs, see also the following chapters in this guide: * Control flow and error handling * Loops and iteration * Functions * Expressions and operators In the next chapter, we will have a look at control flow constructs and error handling. * « 前頁 * 次頁 »
函式 - JavaScript
函式 == * « 前頁 * 次頁 » 函式是構成 javascript 的基本要素之一。一個函式本身就是一段 JavaScript 程序—包含用於執行某一個任務或計算的語法。要呼叫某一個函式之前,你必需先在這個函式欲執行的 scope 中定義它。 定義函式 ---- 一個函式的定義由一系列的函式關鍵詞組成, 依次為: * 函式的名稱。 * 包圍在括號()中,並由逗號區隔的一個函式參數列表。 * 包圍在大括號{}中,用於定義函式功能的一些 JavaScript 語句。 例如,以下的程式碼定義了一個名為 square 的簡單函式: ```js function square(number) { return number \* number; } ``` 函式 square 有一個參數,叫作 number。這個函式只有一行程式碼,它會回傳 number 自乘的結果。函式的 `return` (en-US) 語法描述函式的返回值。 ```js return number \* number; ``` 原始參數(例如一個數字)被作為值傳遞給函式,如果呼叫的函式改變了這個參數的值,不會影響到函式外部的原始變數。 如果傳遞一個物件(例如 `Array` (en-US) 或自定義的其它物件)作為參數,而函式改變了這個物件的屬性,這樣的改變對函式外部是有作用的(因為是傳遞物件的位址),如下面的例子所示: ```js function myFunc(theObject) { theObject.make = "Toyota"; } var mycar = { make: "Honda", model: "Accord", year: 1998 }, x, y; x = mycar.make; // x 的值為 "Honda" myFunc(mycar); y = mycar.make; // y 的值為 "Toyota" // (屬性 make 被 function 改變) ``` 請注意,重新給參數指定一個對象(物件),並不會對函式的外部有任何影響,因為這樣只是改變了參數的值,而不是改變了對象的一個屬性值: ```js function myFunc(theObject) { theObject = { make: "Ford", model: "Focus", year: 2006 }; } var mycar = { make: "Honda", model: "Accord", year: 1998 }, x, y; x = mycar.make; // x 的值為 "Honda" myFunc(mycar); y = mycar.make; // y 的值還是 "Honda" ``` 儘管上述函式定義都是用的是陳述式,函式也同樣可以由函式表達式來定義。這樣的函式可以是匿名的;它不必有名稱。例如,上面提到的函式 square 也可這樣來定義: ```js var square = function (number) { return number \* number; }; var x = square(4); //x 的值為 16 ``` 必要時,函式名稱可與函式表達式同時存在,並且可以用於在函式內部代指其本身(遞迴): ```js var factorial = function fac(n) { return n < 2 ? 1 : n \* fac(n - 1); }; console.log(factorial(3)); ``` 函式表達式在將函式作為一個參數傳遞給其它函式時十分方便。下面的例子展示了一個叫 map 的函式如何被定義,而後呼叫一個匿名函式作為其第一個參數: ```js function map(f, a) { var result = [], // Create a new Array i; for (i = 0; i != a.length; i++) result[i] = f(a[i]); return result; } ``` 下面的程式碼呼叫 map 函式並將一個匿名函式傳入作為第一個參數: ```js map( function (x) { return x \* x \* x; }, [0, 1, 2, 5, 10], ); // 結果會回傳 [0, 1, 8, 125, 1000] ``` 除了上述的定義方式以外,我們也可以透過 `Function` constructor (en-US) 來定義,類似 `eval()`。 呼叫函式 ---- 定義一個函式並不會自動的執行它。定義了函式僅僅是賦予函式以名稱並明確函式被呼叫時該做些什麼。呼叫函式才會以給定的參數真正執行這些動作。例如,一旦你定義了函式 square,你可以如下這樣呼叫它: ```js square(5); ``` 上述程式碼把 5 傳遞給 square 函式。函式執行完會回傳 25。 函式必須在呼叫區塊的可視範圍內,但函數也可以宣告在使用處的下面,如下列範例: ```js console.log(square(5)); /\* ... \*/ function square(n) { return n \* n; } ``` The scope of a function is the function in which it is declared, or the entire program if it is declared at the top level. Note that this works only when defining the function using the above syntax (i.e. `function funcName(){}`). The code below will not work. ```js console.log(square(5)); square = function (n) { return n \* n; }; ``` The arguments of a function are not limited to strings and numbers. You can pass whole objects to a function, too. The `show_props` function (defined in Working with Objects (en-US)) is an example of a function that takes an object as an argument. A function can be recursive; that is, it can call itself. For example, here is a function that computes factorials recursively: ```js function factorial(n) { if (n == 0 || n == 1) return 1; else return n \* factorial(n - 1); } ``` You could then compute the factorials of one through five as follows: ```js var a, b, c, d, e; a = factorial(1); // a gets the value 1 b = factorial(2); // b gets the value 2 c = factorial(3); // c gets the value 6 d = factorial(4); // d gets the value 24 e = factorial(5); // e gets the value 120 ``` There are other ways to call functions. There are often cases where a function needs to be called dynamically, or the number of arguments to a function vary, or in which the context of the function call needs to be set to a specific object determined at runtime. It turns out that functions are, themselves, objects, and these objects in turn have methods (see the `Function` object (en-US)). One of these, the `apply()` (en-US) method, can be used to achieve this goal. Function scope -------------- Variables defined inside a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function. However, a function can access all variables and functions defined inside the scope in which it is defined. In other words, a function defined in the global scope can access all variables defined in the global scope. A function defined inside another function can also access all variables defined in it's parent function and any other variable to which the parent function has access. ```js // The following variables are defined in the global scope var num1 = 20, num2 = 3, name = "Chamahk"; // This function is defined in the global scope function multiply() { return num1 \* num2; } multiply(); // Returns 60 // A nested function example function getScore() { var num1 = 2, num2 = 3; function add() { return name + " scored " + (num1 + num2); } return add(); } getScore(); // Returns "Chamahk scored 5" ``` 閉包 -- 閉包是 JavaScript 最強大的特性之一。JavaScript 允許巢狀函式(nesting of functions)並給予內部函式完全訪問(full access)所有變數、與外部函式定義的函式(還有所有外部函式內的變數與函式)不過,外部函式並不能訪問內部函式的變數與函式。這保障了內部函式的變數安全。另外,由於內部函式能訪問外部函式定義的變數與函式,將存活得比外部函式還久。A closure is created when the inner function is somehow made available to any scope outside the outer function. ```js var pet = function (name) { // The outer function defines a variable called "name" var getName = function () { return name; // The inner function has access to the "name" variable of the outer function }; return getName; // Return the inner function, thereby exposing it to outer scopes }, myPet = pet("Vivie"); myPet(); // Returns "Vivie" ``` It can be much more complex than the code above. An object containing methods for manipulating the inner variables of the outer function can be returned. ```js var createPet = function (name) { var sex; return { setName: function (newName) { name = newName; }, getName: function () { return name; }, getSex: function () { return sex; }, setSex: function (newSex) { if ( typeof newSex == "string" && (newSex.toLowerCase() == "male" || newSex.toLowerCase() == "female") ) { sex = newSex; } }, }; }; var pet = createPet("Vivie"); pet.getName(); // Vivie pet.setName("Oliver"); pet.setSex("male"); pet.getSex(); // male pet.getName(); // Oliver ``` In the codes above, the `name` variable of the outer function is accessible to the inner functions, and there is no other way to access the inner variables except through the inner functions. The inner variables of the inner function act as safe stores for the inner functions. They hold "persistent", yet secure, data for the inner functions to work with. The functions do not even have to be assigned to a variable, or have a name. ```js var getCode = (function () { var secureCode = "0]Eal(eh&2"; // A code we do not want outsiders to be able to modify... return function () { return secureCode; }; })(); getCode(); // Returns the secret code ``` There are, however, a number of pitfalls to watch out for when using closures. If an enclosed function defines a variable with the same name as the name of a variable in the outer scope, there is no way to refer to the variable in the outer scope again. ```js var createPet = function (name) { // Outer function defines a variable called "name" return { setName: function (name) { // Enclosed function also defines a variable called "name" name = name; // ??? How do we access the "name" defined by the outer function ??? }, }; }; ``` The magical `this` variable is very tricky in closures. They have to be used carefully, as what `this` refers to depends completely on where the function was called, rather than where it was defined. An excellent and elaborate article on closures can be found here. Using the arguments object -------------------------- The arguments of a function are maintained in an array-like object. Within a function, you can address the arguments passed to it as follows: ```js arguments[i]; ``` where `i` is the ordinal number of the argument, starting at zero. So, the first argument passed to a function would be `arguments[0]`. The total number of arguments is indicated by `arguments.length`. Using the `arguments` object, you can call a function with more arguments than it is formally declared to accept. This is often useful if you don't know in advance how many arguments will be passed to the function. You can use `arguments.length` to determine the number of arguments actually passed to the function, and then access each argument using the `arguments` object. For example, consider a function that concatenates several strings. The only formal argument for the function is a string that specifies the characters that separate the items to concatenate. The function is defined as follows: ```js function myConcat(separator) { var result = "", // initialize list i; // iterate through arguments for (i = 1; i < arguments.length; i++) { result += arguments[i] + separator; } return result; } ``` You can pass any number of arguments to this function, and it concatenates each argument into a string "list": ```js // returns "red, orange, blue, " myConcat(", ", "red", "orange", "blue"); // returns "elephant; giraffe; lion; cheetah; " myConcat("; ", "elephant", "giraffe", "lion", "cheetah"); // returns "sage. basil. oregano. pepper. parsley. " myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley"); ``` Please note that the `arguments` variable is "array-like", but not an array. It is array-like in that is has a numbered index and a `length` property. However, it does not possess all of the array-manipulation methods. See the `Function` object (en-US) in the JavaScript Reference for more information. Predefined functions -------------------- JavaScript has several top-level predefined functions: * eval * isFinite * isNaN * parseInt and parseFloat * Number and String * encodeURI, decodeURI, encodeURIComponent, and decodeURIComponent (all available with Javascript 1.5 and later). The following sections introduce these functions. See the JavaScript Reference (en-US) for detailed information on all of these functions. ### eval Function The `eval` function evaluates a string of JavaScript code without reference to a particular object. The syntax of `eval` is: ```js eval(expr); ``` where `expr` is a string to be evaluated. If the string represents an expression, `eval` evaluates the expression. If the argument represents one or more JavaScript statements, eval performs the statements. The scope of `eval` code is identical to the scope of the calling code. Do not call `eval` to evaluate an arithmetic expression; JavaScript evaluates arithmetic expressions automatically. ### isFinite function The `isFinite` function evaluates an argument to determine whether it is a finite number. The syntax of `isFinite` is: ```js isFinite(number); ``` where `number` is the number to evaluate. If the argument is `NaN`, positive infinity or negative infinity, this method returns `false`, otherwise it returns `true`. The following code checks client input to determine whether it is a finite number. ```js if (isFinite(ClientInput)) { /\* take specific steps \*/ } ``` ### isNaN function The `isNaN` function evaluates an argument to determine if it is "NaN" (not a number). The syntax of `isNaN` is: ```js isNaN(testValue); ``` where `testValue` is the value you want to evaluate. The `parseFloat` and `parseInt` functions return "NaN" when they evaluate a value that is not a number. `isNaN` returns true if passed "NaN," and false otherwise. The following code evaluates `floatValue` to determine if it is a number and then calls a procedure accordingly: ```js var floatValue = parseFloat(toFloat); if (isNaN(floatValue)) { notFloat(); } else { isFloat(); } ``` ### parseInt and parseFloat functions The two "parse" functions, `parseInt` and `parseFloat`, return a numeric value when given a string as an argument. The syntax of `parseFloat` is: ```js parseFloat(str); ``` where `parseFloat` parses its argument, the string `str`, and attempts to return a floating-point number. If it encounters a character other than a sign (+ or -), a numeral (0-9), a decimal point, or an exponent, then it returns the value up to that point and ignores that character and all succeeding characters. If the first character cannot be converted to a number, it returns "NaN" (not a number). The syntax of `parseInt` is: ```js parseInt(str [, radix]); ``` `parseInt` parses its first argument, the string `str`, and attempts to return an integer of the specified `radix` (base), indicated by the second, optional argument, `radix`. For example, a radix of ten indicates to convert to a decimal number, eight octal, sixteen hexadecimal, and so on. For radixes above ten, the letters of the alphabet indicate numerals greater than nine. For example, for hexadecimal numbers (base 16), A through F are used. If `parseInt` encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. If the first character cannot be converted to a number in the specified radix, it returns "NaN." The `parseInt` function truncates the string to integer values. ### Number and String functions The `Number` and `String` functions let you convert an object to a number or a string. The syntax of these functions is: ```js var objRef; objRef = Number(objRef); objRef = String(objRef); ``` `objRef 是物件的參照`。 Number uses the valueOf() method of the object; String uses the toString() method of the object. 下列範例將 `日期` (en-US) 物件轉換為可讀字串。 ```js var D = new Date(430054663215), x; x = String(D); // x 等於 "星期二 八月 18 04:37:43 GMT-0700 1983" ``` 下列範例將 `字串` (en-US) 物件轉換為 `數字` (en-US) 物件。 ```js var str = "12", num; num = Number(字串); ``` 使用 DOM 方法 `write()` 與 JavaScript `typeof` 運算子. ```js var str = "12", num; document.write(typeof str); document.write("<br/>"); num = Number(str); document.write(typeof num); ``` ### escape 與 unescape 函式(JavaScript 1.5 後去除) `escape` 與 `unescape` 對於非 ASCII 字元無法處理。 在 JavaScript 1.5 之後改用 `encodeURI` (en-US), `decodeURI` (en-US), `encodeURIComponent` (en-US), 與 `decodeURIComponent` (en-US). `escape` 與 `unescape` 用於編碼與解碼字串。 `escape` 函式回傳十六進位編碼。 `unescape` 函式會將十六進位的編碼轉換回 ASCII 字串。 這些函式的語法是: ```js escape(字串); unescape(字串); ``` 這些函式常被用於伺服器後端中處理姓名等資料。
運算式與運算子 - JavaScript
運算式與運算子 ======= * « 前頁 * 次頁 » 這個章節將講述 JavaScript 的運算式與運算子,包括賦值運算子,比較運算子,算術運算子,位元運算子, 邏輯運算子, 字串運算子, 條件(三元)運算子 以及更多運算子. 更多關於運算子以及運算式的資料可以在 reference 中找到。 運算子 --- JavaScript 有以下幾種運算子。 此處將描述運算子以及一些運算子的優先順序。 * 賦值運算子 * 比較運算子 * 算術運算子 * 位元運算子 * 邏輯運算子 * 字串運算子 * 條件(三元)運算子 * 逗點運算子 * 一元運算子 * 關係運算子 JavaScript 同時具有二元運算子及一元運算子, 以及一種特殊的 三元運算子,也就是 條件運算子。 一個二元運算子需要具備兩個運算元, 一個在運算元之前,一個在運算元之後: ``` 運算元1 運算子 運算元2 ``` 例如, `3+4` 或 `x*y`. 一個 一元運算子 需要一個運算元, 位於運算子之前或之後: ``` 運算子 運算元 ``` 或 ``` 運算元 運算子 ``` 例如, `x++` 或 `++x`. ### 賦值運算子 一個 賦值運算子 (en-US) 將 基於其 右方的運算元 的值賦予其 左方的運算元。 最簡單的 賦值運算子 是 等於 (`=`), 它將賦予 左方運算元 與 右方運算元相同之值。 也就是, `x = y` 會把 y 的值賦予給 x。 也有一些復合的 賦值運算子 是為了縮短下面表中的運算: | 名稱 | 簡化的運算子 | 意義 | | --- | --- | --- | | 賦值 (en-US) | `x = y` | `x = y` | | 加法 (en-US)賦值 (en-US) | `x += y` | `x = x + y` | | 減法 (en-US)賦值 (en-US) | `x -= y` | `x = x - y` | | 乘法 (en-US)賦值 (en-US) | `x *= y` | `x = x * y` | | 除法 (en-US)賦值 (en-US) | `x /= y` | `x = x / y` | | 餘數 (en-US)賦值 (en-US) | `x %= y` | `x = x % y` | | 指數 (en-US)賦值 (en-US) | `x **= y` | `x = x ** y` | | 左移賦值 (en-US) | `x <<= y` | `x = x << y` | | 右移賦值 (en-US) | `x >>= y` | `x = x >> y` | | 無號右移賦值 (en-US) | `x >>>= y` | `x = x >>> y` | | 位元 AND 賦值 (en-US) | `x &= y` | `x = x & y` | | 位元 XOR 賦值 (en-US) | `x ^= y` | `x = x ^ y` | | 位元 OR 賦值 (en-US) | `x |= y` | `x = x | y` | #### 解構 為了進行更複雜的賦值,解構賦值是 JavaScript 用來從陣列或物件中提取資料的語法。 ```js var foo = ["one", "two", "three"]; // 不使用解構 var one = foo[0]; var two = foo[1]; var three = foo[2]; // 使用解構 var [one, two, three] = foo; ``` ### 比較運算子 比較運算子 (en-US) 會比較 運算元 並基於比較的結果回傳邏輯值。 運算元可以是數字,字串,邏輯,或物件的值。 字串的比較是基於字典序的, 使用 Unicode 的值。 在多數情況下,假如兩個運算元不具有相同型態, JavaScript 會嘗試將它們轉換成相同型態。這個行為通常是將運算元以數學形式對待。 在某些的轉換型態的例外中會使用到 `===` 及 `!==` 運算子, 它們會嚴格地進行相等或不相等的比較。 這些運算子不會在確認相等與否前嘗試轉換運算元的型態。 下面的表解釋了比較運算子: ```js var var1 = 3; var var2 = 4; ``` | 運算子 | 描述 | 會回傳 True 的例子 | | --- | --- | --- | | 等於 (en-US) (`==`) | 假如運算元等價就回傳 True。 | `3 == var1` `"3" == var1` `3 == '3'` | | 不等於 (en-US) (`!=`) | 假如運算元等價就回傳 True。 | `var1 != 4 var2 != "3"` | | 嚴格等於 (en-US) (`===`) | 假如運算元具有相同型態且等價則回傳 True。參考 `Object.is` (en-US) 及 JS 中的等價性。 | `3 === var1` | | 嚴格不等於 (en-US) (`!==`) | 假如運算元具有相同型態但不等價,或是具有不同型態,回傳 True。 | `var1 !== "3" 3 !== '3'` | | 大於 (en-US) (`>`) | 假如左方運算元大於右方運算元,回傳 True。 | `var2 > var1 "12" > 2` | | 大於或等於 (en-US) (`>=`) | 假如左方運算元大於或等於右方運算元,回傳 True。 | `var2 >= var1 var1 >= 3` | | 小於 (en-US) (`<`) | 假如左方運算元小於右方運算元,回傳 True。 | `var1 < var2 "2" < 12` | | 小於或等於 (en-US) (`<=`) | 假如左方運算元小於或等於右方運算元,回傳 True。 | `var1 <= var2 var2 <= 5` | **備註:** `=>` 不是運算子,是 箭頭函式。 ### 算術運算子 算術運算子 (en-US) 以 數值 (文字或變數也可以)作為其運算元,並回傳單一數值。最常見的算術運算元是 加法 (`+`),減法 (`-`), 乘法 (`*`),及除法 (`/`)。 這些運算子在大多數程式語言中功能相同 (比較特別的是,在除數為 0 時 `Infinity`)。例如: ```js 1 / 2; // 0.5 1 / 2 == 1.0 / 2.0; // 會是 true ``` 除了標準的算術運算子外 (+, -, \* /), JavaScript 提供以下表中的算術運算子: | 運算子 | 描述 | 範例 | | --- | --- | --- | | 取餘數 (en-US) (`%`) | 二元運算子。回傳兩個運算元相除後的餘數。 | 12 % 5 回傳 2. | | 增加 (en-US) (`++`) | 一元運算子。 將運算元增加 1。假如使用在運算元之前 (`++x`),會運算元回傳增加 1 後的值;假如使用在運算元之後。 (`x++`)`,` 會回傳運算元加 1 前的值。 | 假如 `x是` 3,那 `++x` 將把 `x` 設定為 4 並回傳 4,而 `x++ 會回傳` 3 , 接著才把 `x 設定為` 4。 | | 減少 (en-US) (`--`) | 一元運算子。 將運算元減少 1。回傳值的情況與 增加運算元 相同。 | 假如 `x是` 3,那 `--x` 將把 `x` 設定為 2 並回傳 2,而 `x-- 會回傳` 3 , 接著才把 `x 設定為` 2。 | | (一元運算子)減號 (en-US) (`-`) | 一元運算子。回傳運算元的負數。 | 假如 x 是 3,-x 回傳 -3。 | | (一元運算子)加號 (en-US) (`+`) | 一元運算子。嘗試將運算元轉換成數字,假如它還不是數字的話。 | `+"3"` `回傳 3`。 `+true` 回傳 `1.` | | 指數運算子 (en-US) (`**`) 實驗性質 | 計算以 a 為底的 `b` 次方, 也就是, `a^b` | `2 ** 3` `回傳 8`. `10 ** -1` 回傳 `0.1`. | ### 位元運算子 位元運算子 (en-US) 把運算元當作 32 位元的集合來看待 (0 和 1), 而不是十進位,十六進位,或八進位。例如,十進位數字 9 以二進位表示就是 1001。 位元運算子將運算元以上述二進位的形式處理,但是回傳 Javascript 中的數字類型值。 下列表總結了 JavaScript' 中的位元運算子。 | 運算子 | 用法 | 描述 | | --- | --- | --- | | 位元 AND (en-US) | `a & b` | 回傳兩個運算元對於每個 bit 做 AND 的結果。 | | 位元 OR (en-US) | `a | b` | 回傳兩個運算元對於每個 bit 做 OR 的結果。 | | 位元 XOR (en-US) | `a ^ b` | 回傳兩個運算元對於每個 bit 做 XOR 的結果。 | | 位元 NOT (en-US) | `~ a` | 將運算元中的每個 bit 反轉(1->0,0->1)。 | | 左移 (en-US) | `a << b` | 將 `a` 的每個 bit 向左移動 `b` 個 bits,空餘的位數以 0 填滿。 | | 有號右移 (en-US) | `a >> b` | 將 `a` 的每個 bit 向右移動 `b` 個 bits,空餘位數以最高位補滿。 | | 以 0 填充的右移 (en-US) | `a >>> b` | 將 `a` 的每個 bit 向右移動 `b` 個 bits,空餘的位數以 0 填滿。 | #### 位元邏輯運算子 概念上,位元邏輯運算子運作過程如下: * 運算元被轉換為 32 bits 的整數以二進位形式表示 (0 和 1)。大於 32 bits 的數字將被捨棄多出來的位元。例如, 下列整數大於 32 個 bit 但是會被轉換為 32 個 bit 的整數: ``` 轉換之前: 11100110111110100000000000000110000000000001 轉換之後: 10100000000000000110000000000001 ``` * 第一個運算元中的每個 bit 分別對應到第二個運算元的每個 bit: 第一個 bit 對 第一個 bit, 第二個 bit 對 第二個 bit, 以此類推。 * 運算子會對於 bit 進行運算, 結果也是基於 bit 來決定的。 例如, 9 的二元表示法是 1001, 15 的二元表示法是 1111。因此,在使用位元運算子的時候,結果如下: | 運算式 | 結果 | 二元描述式 | | --- | --- | --- | | `15 & 9` | `9` | `1111 & 1001 = 1001` | | `15 | 9` | `15` | `1111 | 1001 = 1111` | | `15 ^ 9` | `6` | `1111 ^ 1001 = 0110` | | `~15` | `-16` | `~ 0000 0000 … 0000 1111 = 1111 1111 … 1111 0000` | | `~9` | `-10` | `~ 0000 0000 … 0000 1001 = 1111 1111 … 1111 0110` | 注意,在使用 位元 NOT 運算子時, 所有的 32 個 bit 都被進行 NOT 了,包含最左邊用來描述正負數的位元(two's-complement representation)。 #### 位元移動運算子 位元移動運算子需要兩個運算元: 第一個是運算的目標,第二個是要移動的位元數。移動的方向取決於使用的運算子。 移動運算子會將運算元轉換成 32 bits 的整數,並且會回傳與左方運算元相同的型態。 移動運算子在下表被列出. | 運算子 | 描述 | 範例 | | --- | --- | --- | | 左移 (en-US) (`<<`) | 這個運算子會將第 一個運算元的每個 bit 向左移動 第二個運算元所指定的 bit 數量。左邊超出的位數會被捨棄,右邊空出的位數以 0 補齊。 | `9<<2` 得到 36,因為 1001 向左移動 2 bits 會得到 100100, 也就是二進位的 36。 | | 有號右移 (en-US) (`>>`) | 這個運算子會將第 一個運算元的每個 bit 向右移動 第二個運算元所指定的 bit 數量。右邊超出的位數會被捨棄,左邊空出的位數以最高位補齊。 | `9>>2` 得到 2,因為 1001 向右移動 2 bits 會得到 10,也就是二進位的 2。 相同的, `-9>>2` 會得到 -3,因為最高位用來表示正負號的 bit 被保留了。 | | 以 0 填充的右移 (en-US) (`>>>`) | 這個運算子會將第 一個運算元的每個 bit 向右移動 第二個運算元所指定的 bit 數量。右邊超出的位數會被捨棄,左邊空出的位數以 0 補齊。 | `19>>>2 得到` 4, 因為 10011 向右移動 2 bits 會得到 100,是二進位的 4。對於非負的數字而言, 以 0 填充的右移 會得到和 有號右移相同的結果。 | ### 邏輯運算子 邏輯運算子 (en-US) 通常被用於布林(邏輯)值; 使用於 布林(邏輯)值時, 它們會回傳布林型態的值。 然而,`&&` 和 `||` 運算子實際上是回傳兩指定運算元之一,因此用於非布林型態值時,它可能會回傳一個非布林型態的值。 邏輯運算子將在下表中被詳細解釋。 | Operator | Usage | Description | | --- | --- | --- | | 邏輯 AND (en-US) (`&&`) | `運算式1 && 運算式2` | 假如 `運算式1` 可以被轉換成 false 的話,回傳 `運算式1`; 否則,回傳 `運算式2`。 因此,`&&`只有在 兩個運算元都是 True 時才會回傳 True,否則回傳 `false`。 | | 邏輯 OR (en-US) (`||`) | `運算式1 || 運算式2` | 假如 `運算式1` 可以被轉換成 true 的話,回傳 `運算式1`; 否則,回傳 `運算式2`。 因此,`||`在 兩個運算元有任一個是 True 時就會回傳 True,否則回傳 `false`。 | | 邏輯 NOT (en-US) (`!`) | `!運算式` | 假如單一個運算元能被轉換成 True 時,回傳`false` , 不然回傳 `true`。 | 可以被轉換為 false 的運算式是 null、0、NaN、空字串(""),或 undefined。 下面是 `&&`(邏輯 AND)運算子的範例。 ```js var a1 = true && true; // t && t 回傳 true var a2 = true && false; // t && f 回傳 false var a3 = false && true; // f && t 回傳 false var a4 = false && 3 == 4; // f && f 回傳 false var a5 = "Cat" && "Dog"; // t && t 回傳 Dog var a6 = false && "Cat"; // f && t 回傳 false var a7 = "Cat" && false; // t && f 回傳 false ``` 下列是 `||`(邏輯 OR)運算子的範例。 ```js var o1 = true || true; // t || t 回傳 true var o2 = false || true; // f || t 回傳 true var o3 = true || false; // t || f 回傳 true var o4 = false || 3 == 4; // f || f 回傳 false var o5 = "Cat" || "Dog"; // t || t 回傳 Cat var o6 = false || "Cat"; // f || t 回傳 Cat var o7 = "Cat" || false; // t || f 回傳 Cat ``` 下列是 `!`(邏輯 NOT)運算子的範例。 ```js var n1 = !true; // !t 回傳 false var n2 = !false; // !f 回傳 true var n3 = !"Cat"; // !t 回傳 false ``` #### 短路解析 邏輯運算式是由左向右解析的, 他們會以下列規則嘗試進行 短路解析: * `false` && *任何東西* 是 false 的短路解析。 * `true` || *任何東西* 是 true 的短路解析。 這些規則保證 解析總是正確的。 值得注意的地方是,剩餘部分的運算式並沒有被解析,所以不會占用任何效能。 ### 字串運算子 除了作為比較運算子之外, 運算子 (+) 也能用於字串,將兩字串接在一起,並回傳接在一起後的結果。 例如, ```js console.log("我的 " + "字串"); // 會印出 字串 "我的字串"。 ``` 簡化的設定運算子 += 也能用於串接字串。 例如, ```js var mystring = "字"; mystring += "母"; // 得到 "字母" 並賦與給變數 mystring. ``` ### 條件(三元)運算子 條件運算子 是 JavaScript 中唯一需要三個運算元的運算子。 這個運算子接受兩個運算元作為值且一個運算元作為條件。 語法是: ``` 條件 ? 值1 : 值2 ``` 如果 *條件* 為 true,運算子回傳 *值 1,* 否則回傳 *值 2。* 你可以在任何使用標準運算子的地方改用 條件運算子。 例如, ```js var status = age >= 18 ? "成人" : "小孩"; ``` 這個陳述句會將 "成人" 賦與給變數 `status` 假如 `age` 大於等於 18。 否則,會將 "小孩" 賦與給變數 `status`。 ### 逗號運算子 逗點運算子 (en-US) (`,`) 作用是解析兩個運算元並回傳後面那個運算元的值。 這個運算子通常用於 for 迴圈內部,讓多個變數能在每次迴圈中被更新。 例如,假如 `a` 是一個有十個物件在裡面的二維陣列, 下面的程式中就使用了逗點運算子來同時更新兩個變數。 這段程式碼會印出陣列中所有對角線上的物件: ```js for (var i = 0, j = 9; i <= j; i++, j--) console.log("a[" + i + "][" + j + "]= " + a[i][j]); ``` ### 一元運算子 一元運算 是只需要一個運算元的運算。 #### `delete` `delete` 運算子會刪除物件,物件的性質,或是陣列中指定 index 的物件。 語法是: ```js delete 物件名稱; delete 物件名稱.性質; delete 物件名稱[索引]; delete 性質; // 只有在 with 陳述句中可以使用 ``` `物件名稱` 是物件的名稱, 性質 是物件中的一個特性, 索引 是用來表示物件在陣列中位置的一個整數。 第四種形式只有在 `with` (en-US) 陳述句中可用, 用來刪除物件中的一個特性。 你可以用 `delete` 運算子來刪除隱式宣告的變數, 但不適用於使用 var 宣告的變數。 假如 `delete` 運算子使用成功, 它會將物件 或是 物件的特性設定為 `未定義。` `delete` 運算子會在運算成功時回傳 true ,失敗時回傳 `false` 。 ```js x = 42; var y = 43; myobj = new Number(); myobj.h = 4; // 建立特性 h delete x; // 回傳 true (只有在隱式宣告時能被刪除) delete y; // 回傳 false (在使用 var 宣告時無法刪除) delete Math.PI; // 回傳 false (不能刪除內建定義的特性) delete myobj.h; // 回傳 true (可以刪除使用者自定義的特性) delete myobj; // 回傳 true (在隱式宣告時可被刪除) ``` ##### 刪除陣列元素 在你刪除了陣列中的一個元素後, 陣列的長度並不會改變。 例如, 假如你`刪除 a[3]`, `a[4]` 依然是 `a[4]` 而 `a[3]` 為 未定義。 當使用 `delete` 運算子刪除陣列中的一個元素後, 那個元素便不再存在於陣列中了。 在下面的程式中, `trees[3]` 被用 delete 移除了。然而, `trees[3]` 的記憶體位址仍可用並且會回傳 未定義。 ```js var trees = ["redwood", "bay", "cedar", "oak", "maple"]; delete trees[3]; if (3 in trees) { // 不會執行到這裡 } ``` 假如你希望給予陣列元素 未定義 的值, 你可以直接使用 `undefined` 關鍵字而不是使用 delete 運算子。 下列範例中, `trees[3]` 被指定了 `undefined`, 然而陣列元素依然存在: ```js var trees = ["redwood", "bay", "cedar", "oak", "maple"]; trees[3] = undefined; if (3 in trees) { // 會執行這裡 } ``` #### `typeof` `typeof` 運算子 能以下列任一方式使用: ``` typeof 運算元 typeof (運算元) ``` `typeof` 運算子會回傳代表運算元類型的 字串。 `運算元能是字串,變數,關鍵字,或是會回傳型態的物件。` 括號是可有可無的。 假設你定義了以下這些變數: ```js var myFun = new Function("5 + 2"); var shape = "round"; var size = 1; var today = new Date(); ``` `typeof` 運算子會回傳下列結果: ```js typeof myFun; // 回傳 "function" typeof shape; // 回傳 "string" typeof size; // 回傳 "number" typeof today; // 回傳 "object" typeof doesntExist; // 回傳 "undefined" ``` 對於 `true` 和 `null關鍵字,` `typeof` 運算子會回傳下列結果: ```js typeof true; // 回傳 "boolean" typeof null; // 回傳 "object" ``` 對於字串或數字, `typeof` 運算子會回傳下列結果: ```js typeof 62; // 回傳 "number" typeof "Hello world"; // 回傳 "string" ``` 對於特性,`typeof` 運算子會回傳 特性的值的類型: ```js typeof document.lastModified; // 回傳 "string" typeof window.length; // 回傳 "number" typeof Math.LN2; // 回傳 "number" ``` 對於 方法 及 函式, `typeof` 運算子會回傳下列結果: ```js typeof blur; // 回傳 "function" typeof eval; // 回傳 "function" typeof parseInt; // 回傳 "function" typeof shape.split; // 回傳 "function" ``` 對於內建定義的物件, `typeof` 運算子會回傳下列結果: ```js typeof Date; // 回傳 "function" typeof Function; // 回傳 "function" typeof Math; // 回傳 "object" typeof Option; // 回傳 "function" typeof String; // 回傳 "function" ``` #### `void` `void` 運算子 (en-US) 能以下列任一方式使用: ``` void (運算式) void 運算式 ``` `void` 運算子會解析運算式而不回傳任何值。 `運算式` 是 JavaScript 中要解析的對象。 括號是可有可無的,但是建議使用。 你可以使用 `void` 運算子來解析超連結中的運算式。 運算式會被解析而不會在當前頁面被印出。 下列範例是一個在點擊時甚麼都不做的超連結。 當使用者點擊連結時, `void(0)` 被解析為 未定義, 而甚麼都不會發生。 ```html <a href="javascript:void(0)">點擊這裡,甚麼都不會發生</a> ``` 下列範例是一個在使用者點擊時傳送表單的超連結。 ```html <a href="javascript:void(document.form.submit())"> 點擊以送出</a> ``` ### 關係運算子 關係運算子比較兩運算元並基於比較結果回傳布林值。 #### `in` `in` 運算子 (en-US)在指定性質存在於物件中時回傳 true。語法是: ```js 性質名稱 in 物件名稱 ``` 性質名稱 可以是 字串或數字,或是陣列的索引, 且物件名稱是物件的名稱。 下列範例示範了 `in` 運算子的一些用法。 ```js // 陣列 var trees = ["redwood", "bay", "cedar", "oak", "maple"]; 0 in trees; // 回傳 true 3 in trees; // 回傳 true 6 in trees; // 回傳 false "bay" in trees; // 回傳 false (你必須指定 索引, // 而不是 索引所對應的元素) "length" in trees; // 回傳 true (length 是陣列的性質之一) // 內建物件 "PI" in Math; // 回傳 true var myString = new String("coral"); "length" in myString; // 回傳 true // 自訂義物件 var mycar = { make: "Honda", model: "Accord", year: 1998 }; "make" in mycar; // 回傳 true "model" in mycar; // 回傳 true ``` #### `instanceof` `instanceof` 運算子 (en-US) 在 指定物件 具有 指定的物件型態 時回傳 true。 語法是: ``` 物件名稱 instanceof 物件類型 ``` `物件名稱` 是用來與 物件類型 比較的物件的名字, 物件類型 是物件的類型, 例如 `Date` 或 `Array`。 當你需要在程式執行中確認物件的形態時,你可以使用 ins`tanceof` 運算子。 例如,當捕捉到例外時, 你可以依照例外的類型來決定用來處理意外的程式碼。 例如,下列程式碼使用 `instanceof` 來判斷變數 `theDay` 是不是 `Date` 類型的物件。 因為 `theDay` 是 `Date` 類型的物件, 所以 if 陳述中的陳述句會被執行。 ```js var theDay = new Date(1995, 12, 17); if (theDay instanceof Date) { // 會被執行的陳述 } ``` ### 運算子優先級 運算子優先級決定運算子被使用於運算元的先後順序。 你也可以使用括號來強制指定優先級。 下列表格列出了運算子的優先級, 從高到低。 | 運算子類型 | 屬於該類別的運算子 | | --- | --- | | 成員 | `. []` | | 呼叫/建立 實例 | `() new` | | 反向/增加 | `! ~ - + ++ -- typeof void delete` | | 乘法/除法 | `* / %` | | 加法/減法 | `+ -` | | 位元移動 | `<< >> >>>` | | 關係運算子 | `< <= > >= in instanceof` | | 相等性 | `== != === !==` | | 位元 and | `&` | | 位元 xor | `^` | | 位元 or | `|` | | 邏輯 and | `&&` | | 邏輯 or | `||` | | 條件運算子 | `?:` | | 指定運算子 | `= += -= *= /= %= <<= >>= >>>= &= ^= |=` | | 逗點運算子 | `,` | 這個表格更詳細的版本,解釋了運算子的更多細節和關聯性, 可以在 JavaScript 參考 中被找到。 運算式 --- 運算式是任何一段可以取得一個值的程式碼。 任何合乎語法的運算式都能取得一個值,概念上, 有兩種不同型態的運算式: 有副作用的 (例如: 將一個值指定給一個變數) 以及只為了取得值而解析的運算式。 運算式 `x = 7` 是上述的第一種類型。這個使用 = 運算子的運算式會將數值 7 賦與給 x。 運算式本身也會被解析為 7。 運算式 `3 + 4` 是上述的第二種類型。這個運算式使用 + 運算子把 3 和 4 加起來,而不指定給任何變數。 JavaScript 運算式有下列幾種種類: * 算術: 解析出數字, 例如 3.14159。(通常使用算術運算子。) * 字串: 解析出字串, 例如 "Fred" or "234"。(通常使用字串運算子。) * 邏輯: 解析出 True 或 False(通常與邏輯運算子相關。) * 主流運算式: JavaScript 基本的關鍵字及運算式。 * 左側運算式: 左側是指定值的對象。 ### 主流運算式 JavaScript 基本的關鍵字及運算式。 #### `this` `this` 關鍵字 能取得當前所在物件。 一般而言, `this` 能取得呼叫處所在的物件。 你可以使用 點 或是 中括號 來取用該物件中的特性: ``` this['特性名稱'] this.特性名稱 ``` 以下定義一個叫做 `validate` 的函式,比較物件中特性 `value 與傳入的兩變數`: ```js function validate(obj, lowval, hival) { if (obj.value < lowval || obj.value > hival) console.log("不可用的值!"); } ``` 你可以在表單的 `onChange` event handler 中呼叫 `validate` 函式, 並以 `this` 來傳入表單的元素, 範例如下: ```html <p>請輸入一介於18 與 99 的數字:</p> <input type="text" name="age" size="3" onChange="validate(this, 18, 99);" /> ``` #### 分組運算子 分組運算子 `( )` 控制了運算子的優先順序。 例如,你可以覆寫先乘除,後加減的優先順序,使其變成先加減,後乘除。 ```js var a = 1; var b = 2; var c = 3; // 預設運算級 a + b \* c; // 7 // 預設的結果 a + (b \* c)( // 7 // 現在複寫運算級 // 變成先進行加法,後乘法了 a + b, ) \* c; // 9 // 結果 a \* c + b \* c; // 9 ``` #### 解析 解析是 JavaScript 中的一個實驗性功能, 在未來版本的 ECMAScript 計畫被導入。有兩種不同類型的解析: 實驗性質 `[for (x of y) x]` (en-US) 陣列解析。 實驗性質 `(for (x of y) y)` (en-US) 產生器解析。 解析在許多程式語言中都存在,允許你快速地基於現存陣列產生新的陣列,例如: ```js [for (i of [ 1, 2, 3 ]) i\*i ]; // [ 1, 4, 9 ] var abc = [ 'A', 'B', 'C' ]; [for (letters of abc) letters.toLowerCase()]; // [ 'a', 'b', 'c' ] ``` ### 左側運算式 左側是指定值的對象。 #### `new` 你可以使用 `new` 運算子 來建立一個使用者自定義物件或內建物件的實例。 用法如下: ```js var 物件名稱 = new 物件型態([參數1, 參數2, ..., 參數N]); ``` #### super super 關鍵字用於呼叫物件的父物件中的函式。在使用類別來呼叫父類別的建構子時很實用,例如: ``` super([參數]); // 呼叫父物件的建構子. super.父物件的函式([參數]); ``` #### 展開運算子 展開運算子 (en-US)能將運算式展開於需要多個參數的地方(如函式呼叫)或是需要多個元素(如陣列字串常數)的地方。 **範例**:現在你想要用已存在的一個陣列做為新的一個陣列的一部份,當字串常數不再可用而你必須使用指令式編程,也就是使用,一連串的 `push`、`splice`、`concat`,等等。展開運算子能讓過程變得更加簡潔: ```js var parts = ["肩膀", "膝蓋"]; var lyrics = ["頭", ...parts, "和", "腳趾"]; ``` 相同的,展開運算子也適用於函式呼叫: ```js function f(x, y, z) {} var args = [0, 1, 2]; f(...參數); ``` * « 前頁 * 次頁 »
Loops and iteration - JavaScript
Loops and iteration =================== * « 前頁 * 次頁 » 迴圈提供一個快速又簡潔的方法來重複地做某件事。這個章節的JavaScript 教學會介紹在 JavaScript 可以使用的幾種不同的迭代陳述式。 你可以將迴圈想成一個電腦版本的"往一個方向走 X 步,然後往另一個方向走 Y 步"的遊戲;作為範例,"往東走五步"可以用這個方法用迴圈表示: ```js var step; for (step = 0; step < 5; step++) { // 執行五次:從step為0到4 console.log("Walking east one step"); } ``` 有很多種不同種類的迴圈, 不過他們本質上都是做一樣的事:把一件動作重複地做一定的次數(而且也有可能做 0 次)。 各式各樣的迴圈機制提供了不同的方法來定義該迴圈的起始與結束。有些不同的情況下使用其中一種迴圈會比使用別種容易許多。 在 javaScript 中提供的迴圈陳述式分別為: * for 陳述式 * do...while 陳述式 * while 陳述式 * label 陳述式 * break 陳述式 * continue 陳述式 * for...in 陳述式 * for...of 陳述式 `for` 陳述式 --------- 一個for 迴圈不斷重複直到一個指定的條件式判斷為 false。JavaScript 的 for 迴圈跟 Java 還有 C 的 for 迴圈很相似。一個 for 陳述式看起來像下面這樣: ``` for ([初始表達式]; [條件式]; [遞增表達式]) 陳述式 ``` 當執行一個 for 迴圈時,會發生以下: 1. 如果有的話,初始表達式會被執行。這個表達式通常會初始化一或多個迴圈計數器,但是語法允許任何程度的複雜性。這個表達式也能用來宣告變數。 2. 條件式會被評估。如果評估出的值為 true,迴圈的敘事式便會執行。如果評估出的值為 false,這個 for 迴圈便會中止。如果條件式被省略了,狀態就會被假設是 true。 3. 執行敘事式。要執行多個敘事式時,使用區塊敘事式(`{ ... }`) 來把那些敘事式歸為一組。 4. 如果有更新表達式的遞增表達式便執行。然後 return 到第二步。 ### 範例 以下的函式包含一個用來數在一個滾動列表中被選過的選項(a `<select>` (en-US) 允許複數選項的元素)的 for 陳述式 。這個 for 敘事式宣告了變數 i 並將其初始化為 0。 他檢查 i ,如果 i 少於在<select>元素中的選項數量,進行接著的 if 陳述式,並將 i 在每次通過迴圈後遞增。 ```html <form name="selectForm"> <p> <label for="musicTypes" >Choose some music types, then click the button below:</label > <select id="musicTypes" name="musicTypes" multiple="multiple"> <option selected="selected">R&B</option> <option>Jazz</option> <option>Blues</option> <option>New Age</option> <option>Classical</option> <option>Opera</option> </select> </p> <p><input id="btn" type="button" value="How many are selected?" /></p> </form> <script> function howMany(selectObject) { var numberSelected = 0; for (var i = 0; i < selectObject.options.length; i++) { if (selectObject.options[i].selected) { numberSelected++; } } return numberSelected; } var btn = document.getElementById("btn"); btn.addEventListener("click", function () { alert( "Number of options selected: " + howMany(document.selectForm.musicTypes), ); }); </script> ``` `do...while` 陳述式 ---------------- `do...while` 陳述式會不斷重複直到一個特定的條件判斷為 false。一個 do...while 陳述式看起來像以下: ``` do 陳述式 while (條件式); ``` `陳述式會在檢查條件式以前先執行一次。要執行多個陳述式的話,使用區塊陳述式來將那些陳述式歸為一組。如果條件式為true,那陳述式便再次執行。在每次執行的最後,條件會被檢查。當條件式為false時,` 停止執行並把控制傳給 `do...while接著的陳述式。` ### 範例 在下列範例中,do 迴圈重複了至少一次並不斷重複直到 i 不再比 5 少。 ```js var i = 0; do { i += 1; console.log(i); } while (i < 5); ``` `while` 陳述式 ----------- `while` 陳述式會不斷執行它的陳述式只要指定的條件式判斷為 true。一個 while 陳述式看起來如下: ``` while (condition) statement ``` 如果條件式變成 false ,在迴圈中的陳述式會停止執行並控制交給跟在這個迴圈後面的陳述式。 條件式的測試發生於迴圈內的陳述式執行之前。如果條件式傳回 true ,陳述式便會被執行而判斷式會再被測試一次。如果條件式傳回 false ,停止執行並把控制交給跟在 while 迴圈後面的陳述式。 `要執行多個陳述式的話,使用區塊陳述式來將那些陳述式歸為一組。` ### 範例 1 以下的 while 迴圈在只要 n 比 3 少的情況下便會不斷重複: ```js var n = 0; var x = 0; while (n < 3) { n++; x += n; } ``` 在每次的疊代,迴圈把 n 遞增並將其值加到 x 上。因此,x 跟 n 的值會是下列情況: * 經過第一次迴圈後 `n` = 1 而 `x` = 1 * 經過第二次迴圈後 `n` = 2 而 `x` = 3 * 經過第三次迴圈後 `n` = 3 而 `x` = 6 在完成第三次迴圈後,判斷是 n<3 不再是 true ,所以迴圈終止。 ### 範例 2 避免無限迴圈。確定在迴圈內的判斷式終究會變成 false; 不然迴圈會永遠不終止。在迴圈內的陳述式會永遠的執行因為判斷式永遠不會變成 false: ```js while (true) { console.log("Hello, world"); } ``` `label` 陳述式 ----------- label 提供一個有識別字的陳述式讓你能在程式的別的地方參考。舉個例子,你能使用 label 來識別一個迴圈,然後使用 break 或 continue 陳述式來指示何時程式該中斷迴圈或是繼續他的執行。 label 陳述式的語法看起來如下: ``` label : statement ``` Label 的值可以是任何不是保留字的 JavaScript 識別字。你用 label 所識別的陳述式可以是任何陳述式。 ### 範例 在這個範例,`markLoop這個label 識別一個while 迴圈。` ```js markLoop: while (theMark == true) { doSomething(); } ``` `break` 陳述式 ----------- `break` 陳述式是用來終止一個迴圈,一個 switch 多重控制選項,或是和一個 label 陳述式聯合使用。 * 當你在沒有 label 的情況下使用 break,它會馬上終止最內部的 while , do-while , for ,或是 switch 區間並將控制交給接下來的陳述式。 * 當你跟 label 一起使用的時候,它會終止那個特定的被 label 的陳述式。 break 陳述式的語法看起來如下: 1. `break;` 2. `break label;` 第一種語法會終止最內部的迴圈或 switch 區間;第二種語法會終止那個特定的 label 陳述式。 ### 範例 1 以下的範例會不斷重複跑迴圈直到有在陣列裡的元素符合 theValue 的值: ```js for (var i = 0; i < a.length; i++) { if (a[i] == theValue) { break; } } ``` ### 範例 2:Break 至一個 label 陳述式 ```js var x = 0; var z = 0; labelCancelLoops: while (true) { console.log("Outer loops: " + x); x += 1; z = 1; while (true) { console.log("Inner loops: " + z); z += 1; if (z === 10 && x === 10) { break labelCancelLoops; } else if (z === 10) { break; } } } ``` `continue` 陳述式 -------------- `continue` 陳述式可以用於重新開始一個 while , do-while, for, 或 label 陳述式。 * 當你在沒有 label 的情況下使用 continue,它會終止現在最內部 while, do-while , for 陳述式區間的迭代並繼續執行該迴圈的下一個迭代。跟 break 陳述式不同的是,continue 不會把整個迴圈的執行給終止。在 while 迴圈中,它會跳回條件式的判斷。在 for 迴圈中,它會跳至遞增陳述式。 * 當 contunue 跟 label 一起使用的時候,它會應用至被 label 識別的那個迴圈陳述式。 continue 陳述式的語法看起來如下: 1. `continue;` 2. `continue`*`label;`* ### 範例 1 以下的範例有 while 迴圈以及一個在 i 的值為 3 的時候執行的 continue 陳述式。因此,n 的值會連著是 1, 3, 7, 12。 ```js var i = 0; var n = 0; while (i < 5) { i++; if (i == 3) { continue; } n += i; } ``` ### 範例 2 一個被 label 成 checkiandj 的陳述式包還著一個被 label 成 checkj 的陳述式。如果遇到了 continue,程式會終止現在的這輪迴圈並開始下一輪。每次遇到 continue,checkj 就會一直重複直到它的條件式返回 false。當 false 被傳回時,checkiandj 陳述式剩下的陳述式已被完成,而 checkiandj 也會繼續重複直到它的條件式傳回 false。當 false 被傳回,程式會繼續進行接著 checkiandj 後面的陳述式。 如果 continue 有了 checkiandj 的 label 程式會從 checkiandj 陳述式的頭開始繼續。 ```js checkiandj: while (i < 4) { console.log(i); i += 1; checkj: while (j > 4) { console.log(j); j -= 1; if (j % 2 == 0) { continue checkj; } console.log(j + " is odd."); } console.log("i = " + i); console.log("j = " + j); } ``` `for...in` 陳述式 -------------- `for...in` 陳述式重複一個指定的變數來循環一個物件所有可枚舉的屬性。至於每個獨特的屬性,JavaScript 執行特定的陳述式。一個`for...in` 陳述式看起來像以下: ``` for (variable in object) { statements } ``` ### 範例 以下的函式透過它的參數得到一個物件和物件的名字。接著它循環這個物件的所有屬性並傳回一個列出屬性名和值的字串。 ```js function dump\_props(obj, obj\_name) { var result = ""; for (var i in obj) { result += obj_name + "." + i + " = " + obj[i] + "<br>"; } result += "<hr>"; return result; } ``` 對於一個擁有 make 跟 model 屬性的物件 car 來說,執行結果是: ```js car.make = Ford; car.model = Mustang; ``` ### 陣列 雖然用 for...in 來迭代 `Array` 元素很吸引人,但是它傳回的除了數字的索引之外還有可能是你自己定的屬性名。因此還是用帶有數字索引的傳統`for迴圈來迭帶一個陣列會比較好。因為如果你想改變陣列物件,比如增加屬性或是方法,`**for...in** 陳述式迭代的是自定的屬性而不是陣列的元素。 `for...of` 陳述式 -------------- `for...of` (en-US) 陳述式在iterable objects (en-US)(可迭代的物件)上建立了一個循環 (包含 `Array`, `Map`, `Set`, arguments (en-US)(參數) 物件 等等), 對每個獨特屬性的值使用一個準備被執行的有陳述式的自訂迭代掛勾。 ``` for (variable of object) { statement } ``` 下列的範例可看出`for...of` 迴圈跟 `for...in` 迴圈的差別。 `for...in` 在屬性名字循環,而`for...of` 在屬性的值循環。 ```js let arr = [3, 5, 7]; arr.foo = "hello"; for (let i in arr) { console.log(i); // logs "0", "1", "2", "foo" } for (let i of arr) { console.log(i); // logs 3, 5, 7 } ``` * « 前頁 * 次頁 »
JavaScript 概觀 - JavaScript
JavaScript 概觀 ============= * « 前頁 * 次頁 » 這個章節的內容主要是介紹 JavaScript 和討論一些 JavaScript 的基本概念。 在開始前需具備之能力 ---------- 本手冊假設你具有以下基本背景: * 對網際網路及全球資訊網有大致上的了解 * 對 HTML(HyperText Markup Language )語法理解至一定程度 * 有寫過程式的經驗,若你是完全的新手,可嘗試在主頁上有關JavaScript的教程。 什麼是 JavaScript? --------------- JavaScript 是個跨平台、物件導向、輕小型的腳本語言。作為獨立語言並不實用,而是為了能簡單嵌入其他產品和應用程式(例如:網頁瀏覽器)而設計。JavaScript 若寄宿在主體環境(Host environment)時,可以與環境中的物件 (Object)相連,並以程式控制這些物件。 Core JavaScript 包含了物件的核心集合(例如: `Array、` `Date、` `Math`)及語言成份的核心集合(例如:運算子、控制結構、敘述)。在 Core JavaScript 增加額外的物件即可擴充各式各樣的功能,例如: * 用戶端 - JavaScript 藉由提供物件來擴增核心語言達到控制網頁瀏覽器和其文件物件模型(DOM,Document Object Model)的目的。 舉例來說:用戶端的擴充套件允許某個應用程式將元素放置在 HTML 的表單上及對使用者的操作(例如:滑鼠點選、表單輸入、頁面導覽等)做出回應。 * 伺服器端 - JavaScript 藉由提供和伺服器上執行 JavaScript 相關的物件來擴增核心語言。 舉例來說:伺服器端的擴充套件允許某個應用程式和相關的資料庫交換訊息、對一個其他應用程式的呼叫提供連續性的資訊、在伺服器上執行檔案操作。 透過 JavaScript 的 LiveConnect 功能,你可以使 Java 和 JavaScript 的程式碼彼此相連。在 JavaScript 的程式碼中,你可以實例化(instantiate)Java 的物件並存取那些物件的公有方法(public methods)及欄位(fields)。在 Java 的程式碼中,你可以存取 JavaScript 的物件、屬性(properties)及方法(methods)。 Netscape 公司發明了 JavaScript ,而 JavaScript 的第一次使用正是在 Netscape 自家的瀏覽器上。 JavaScript 與 Java ----------------- JavaScript 與 Java 在某些方面非常相似但本質上卻是不同的。 JavaScript 雖然和 Java 類似,卻沒有 Java 的靜態定型(static typing)及強型態確認(strong type checking)特性。 JavaScript 遵從大部份的 Java 表達式語法、命名傳統和基本的流程控制概念,這特性同時也是為何要將 LiveScript 重新命名為 JavaScript 的原因。 相較於 Java 由許多類別中的宣告建立的 compile-time 系統,JavaScript 支援一個由少數代表數值(numeric)、布林值(Boolean)、字串(string)的資料類型所構成的執行期函式庫(runtime system)。JavaScript 擁有一個基於原型的物件模型(prototype-based object model)而不是普遍使用的基於類別的物件模型(class-based object model)。基於原型的物件模型提供動態繼承(dynamic inheritance)的功能,意即被繼承的物件可以根據個別的物件而改變。JavaScript 也支援不需任何特殊宣告的函式,函式可以是物件的屬性,如同鬆散型態方法(loosely typed method)那樣執行。 JavaScript 和 Java 相比起來,算是一個格式非常自由的語言。你不需要宣告所有的變數、類別(class)、方法,你不需要注意哪些方法是公有(public)或私有(private)或受保護的(protected),你不需要實作介面(interface)。變數、參數及函式回傳的型態並不是顯性型態。 Java 是一個為了快速執行與安全型態而設計的基於類別的程式語言(class-based programming language)。安全型態意即你在 Java 中無法將整數丟給一個物件參考,也無法藉由中斷 Java bytecodes 來存取私有的記憶體。 Java 的基於類別模型(class-based model)意思是程式由專門的類別及其方法所組成。Java 的類別繼承(class inheritance)和強型別(strong typing)通常需要嚴謹的耦合對象階級(coupled object hierarchies)。這些需求使得 Java 在程式的撰寫上比 JavaScript 來的複雜。 相反的,JavaScript 承襲了如同 HyperTalk 和 dBASE 相同的精神:較小、動態類型。 這些腳本語言因為較簡單的語法、特殊化的功能、較寬鬆的要求等特性,進而提供了許多軟體開發工具(programming tool)給更多更廣大的愛好者。 表 1.1 - JavaScript 和 Java 比較 | JavaScript | Java | | --- | --- | | 物件導向。物件的型態之間無區別。藉由原型機制(prototype mechanism)和屬性(properties)實行繼承。屬性和方法可被動態新增至任何物件。 | 類別導向。物件藉由類別階級(class hierarchy)而被分離至類別和所有繼承的實體(instance)中。類別和實體無法動態新增屬性和方法。 | | 變數資料型態沒有宣告就可使用(動態定型,dynamic typing)。 | 變數資料型態必須宣告才可使用(靜態定型,static typing)。 | | 無法自動覆寫到硬碟。 | 無法自動覆寫到硬碟。 | 更多關於 JavaScript 和 Java 的差異比較,請參見 Details of the Object Model 。 JavaScript 與 ECMAScript 規格 -------------------------- Netscape 公司發明了 JavaScript ,而 JavaScript 的第一次應用正是在 Netscape 瀏覽器。然而,Netscape 後來和 Ecma International(一個致力於將資訊及通訊系統標準化的歐洲組織,前身為 ECMA - 歐洲計算機製造商協會)合作,開發一個基於 JavaScript 核心並同時兼具標準化與國際化的程式語言,這個經過標準化的 JavaScript 便稱作 ECMAScript ,和 JavaScript 有著相同的應用方式並支援相關標準。各個公司都可以使用這個開放的標準語言去開發 JavaScript 的專案。ECMAScript 標準記載於 ECMA-262 這個規格中。 ECMA-262 標準同時也經過 ISO(國際標準化組織)認証,成為 ISO-16262 標準。你可以在 Mozilla 的網站上找到 PDF 版本的 ECMA-262,但這板本已過期;你也可以在 Ecma International 的網站 找到這個規格。 ECMAScript 規格中並沒有描述已經被 W3C(全球資訊網協會)標準化的文件物件模型(DOM)。文件物件模型定義了 HTML 文件物件(document objects)和腳本之間運作的方式。 ### JavaScript 版本與 ECMAScript 版本之間的關係 ECMAScript 規格(ECMA-262)在 Netscape 和 Ecma International 的密切合作下產生。下表描述了 JavaScript 的版本和 ECMAScript 的版本之間的關係。 表 1.2 - JavaScript 版本及 ECMAScript 版本 | JavaScript 的版本 | 和 ECMAScript 版本的關係 | | --- | --- | | JavaScript 1.1 | ECMA-262 第1版是基於 JavaScript 1.1 建立的。 | | JavaScript 1.2 | ECMA-262 在 JavaScript 1.2 發行之際尚未完成。以下是 JavaScript 1.2 並未完全相容於 ECMA-262 第1版的原因: * Netscape 在 JavaScript 1.2 中新增了一些特性,而這些特性在 ECMA-262 並未被考慮到。 * ECMA-262 新增了兩個新的特性:使用國際化的 Unicode 編碼及統一了不同平台之間的行為。JavaScript 1.2 中的一些特性,例如:日期物件(Date object)是具有平台依賴性(platform-dependent)並且使用平台特製化行為(platform-specific behavior)的。 | | JavaScript 1.3 | JavaScript 1.3 完全相容於 ECMA-262 第1版。JavaScript 1.3 藉由保留所有在 JavaScript 1.2 新增的特性(除了 == 和 != 以外,因為要和 ECMA-262 一致),解決了 JavaScript 1.2 和 ECMA-262 之間的衝突。 | | JavaScript 1.4 | JavaScript 1.4 完全相容於 ECMA-262 第1版。ECMAScript 第3版規格在 JavaScript 1.4 發行之際尚未完成。 | | JavaScript 1.5 | JavaScript 1.5 完全相容於 ECMA-262 第3版。 | **備註:** ECMA-262 第 2 版是由已修正錯誤的第 1 版並加上些微的更動構成。現今由 Ecma International 的 TC39 工作組(TC39 Working Group)所發行的版本是 ECMAScript 5.1 版 JavaScript Reference (en-US) 指出了哪些 JavaScript 的特性是相容於 ECMAScript 的。 JavaScript 永遠包含許多非 ECMAScript 規格中的特性; JavaScript 不僅相容於 ECMAScript 更提供了額外的特性。 ### JavaScript 使用說明 v.s ECMAScript 規格 ECMAScript 規格是執行 ECMAScript 所必須的條件,當你想判斷某個 JavaScript 的特性是否在其他 ECMAScript 實作中有被支援時,ECMAScript 規格是非常有用的。如果你打算撰寫 JavaScript 程式碼並在程式碼中使用僅有 ECMAScript 所支援的特性,那你可能需要查閱一下 ECMAScript 規格。 ECMAScript 文件並不是為了幫助腳本程式設計師而撰寫,如果想知道撰寫腳本的相關資訊,請參考 JavaScript 使用說明。 ### JavaScript 和 ECMAScript 的專門術語 ECMAScript 規格使用的術語和語法對於 JavaScript 的程式設計師來說可能不是那麼的親切。雖然語言的描述在 ECMAScript 中可能會有所不同,但語言本身的性質仍然是不變的。JavaScript 支援所有在 ECMAScript 規格中被描述到的功能。 JavaScript 使用說明對於語言的觀點的描述較適合 JavaScript 的程式設計師。例如: * 因為全域物件(Global Object)並不會被直接使用,所以並沒有在 JavaScript 文件說明中被論及。而像是全域物件的方法和屬性這些有被使用到的,就有在 JavaScript 使用說明中被論及,但被稱作頂層(top-level)函式和頂層屬性。 * 無參數建構函式(no parameter constructor,也稱作零參數建構函式,zero-argument constructor)。帶有 Number 物件及 String 物件的無參數建構函式並沒有在 JavaScript 使用說明中被論及,因為其產生出來的東西用途有限:一個沒有參數的 Number 建構函式回傳 +0 、一個沒有參數的 String 建構函式回傳 "" (一個空字串)
JavaScript 型別陣列 - JavaScript
JavaScript 型別陣列 =============== * « 前頁 * 次頁 » (en-US) 當 Webapp 有了視頻、音頻操作,及用 WebSocket 存取原始資料等等的功能而變得越來越強大,讓 JavaScript 代碼可以快速、簡單地操作原始二進制資料的好處就越來越明顯。以前唯一的解法是視原始資料為字串並用 `charCodeAt()` (en-US) 方法讀取資料緩衝的位元組。 然而,由於需要多次型別轉換(特別是二進制資料並非以位元組計算,如 32 位元整數或浮點數),這個解法既慢又容易發生錯誤。 JavaScript 型別陣列提供了存取二進制資料更有效率的機制。 型別陣列不該與一般的陣列搞混,當對型別陣列呼叫`Array.isArray()`時會回傳`false`。此外,一般陣列所提供的方法並非全部被型別陣列所支援(如 push 以及 pop 方法) 緩衝與視圖:型別陣列的架構 ------------- 為了追求最大的可朔性與效率,JavaScript 型別陣列的實作分為**緩衝**與**視圖**。一個緩衝(以類別 `ArrayBuffer` 實作)為代表一塊資料資料的物件,它沒有任何格式,也沒有任何存取其內容的機制。想存取一個緩衝所佔的記憶體必須用一個視圖。一個視圖提供了一種前後關係 — 資料型別、起始偏移與元素的數目 — 使得資料變成真實的型別陣列。視圖以類別 `ArrayBufferView` 與其子類別實作。 ![Typed arrays in an ArrayBuffer](/zh-TW/docs/Web/JavaScript/Guide/Typed_arrays/typed_arrays.png) ### ArrayBuffer `ArrayBuffer` 是一種資料型態,用於表示通用的固定長度二進制資料緩衝區。 你不能直接操作 `ArrayBuffer` 的內容。但是,你可以建立一個型別陣列視圖 (typed array view) 或一個 `DataView` (en-US),它以特定格式代表緩衝區,並使用它讀取和寫入緩衝區的內容。 ### 型別陣列視圖 (Typed array views) 型別陣列視圖具有自述性名稱,並為所有常用的數字類型(如 `Int8`, `Uint32`, `Float64` 等)提供視圖。 有一個特殊的型別陣列視圖 `Uint8ClampedArray`。 它的範圍值在 0 到 255 之間。它對於 Canvas 的資料處理非常有用。 | Type | Value Range | Size in bytes | Description | Web IDL type | Equivalent C type | | --- | --- | --- | --- | --- | --- | | `Int8Array` (en-US) | -128 to 127 | 1 | 8-bit two's complement signed integer | `byte` | `int8_t` | | `Uint8Array` (en-US) | 0 to 255 | 1 | 8-bit unsigned integer | `octet` | `uint8_t` | | `Uint8ClampedArray` (en-US) | 0 to 255 | 1 | 8-bit unsigned integer (clamped) | `octet` | `uint8_t` | | `Int16Array` (en-US) | -32768 to 32767 | 2 | 16-bit two's complement signed integer | `short` | `int16_t` | | `Uint16Array` (en-US) | 0 to 65535 | 2 | 16-bit unsigned integer | `unsigned short` | `uint16_t` | | `Int32Array` (en-US) | -2147483648 to 2147483647 | 4 | 32-bit two's complement signed integer | `long` | `int32_t` | | `Uint32Array` (en-US) | 0 to 4294967295 | 4 | 32-bit unsigned integer | `unsigned long` | `uint32_t` | | `Float32Array` (en-US) | 1.2x10^-38 to 3.4x10^38 | 4 | 32-bit IEEE floating point number ( 7 significant digits e.g. 1.1234567) | `unrestricted float` | `float` | | `Float64Array` (en-US) | 5.0x10^-324 to 1.8x10^308 | 8 | 64-bit IEEE floating point number (16 significant digits e.g. 1.123...15) | `unrestricted double` | `double` | ### DataView The `DataView` (en-US) is a low-level interface that provides a getter/setter API to read and write arbitrary data to the buffer. This is useful when dealing with different types of data, for example. Typed array views are in the native byte-order (see Endianness (en-US)) of your platform. With a `DataView` you are able to control the byte-order. It is big-endian by default and can be set to little-endian in the getter/setter methods. Web APIs using typed arrays --------------------------- `FileReader.prototype.readAsArrayBuffer()` The `FileReader.prototype.readAsArrayBuffer()` method starts reading the contents of the specified `Blob` or `File`. `XMLHttpRequest.prototype.send()` `XMLHttpRequest` instances' `send()` method now supports typed arrays and `ArrayBuffer` objects as argument. `ImageData.data` (en-US) Is a `Uint8ClampedArray` (en-US) representing a one-dimensional array containing the data in the RGBA order, with integer values between `0` and `255` inclusive. 範例 -- ### 使用視圖與緩衝 先來建立一個 16 位元組的緩衝: ```js var buffer = new ArrayBuffer(16); ``` 在這個時候,我們有位元組全部初始為 0 的一塊記憶體,但是用它做不了什麼事。我們只能確認它的確是 16 的位元組的長度: ```js if (buffer.byteLength === 16) { console.log("沒錯,是 16 個位元組。"); } else { console.log("糟糕,長度不對!"); } ``` 要用這個緩衝搞點花樣之前,建立一個視圖是必需的。來建立一個視圖把這個緩衝當作 32 位元的有符號整數: ```js var int32View = new Int32Array(buffer); ``` 這樣就可以把它當作一般的陣列以存取欄位: ```js for (var i = 0; i < int32View.length; i++) { int32View[i] = i \* 2; } ``` 這會把此陣列的四個欄位以 0、2、4、6 填滿(四個 4 位元組,總共 16 位元組)。 ### 同一份資料的多個視圖 考慮在同一份資料上建立多個視圖的有趣情形。舉例來說,繼續使用上面的代碼: ```js var int16View = new Int16Array(buffer); for (var i = 0; i < int16View.length; i++) { console.log("Entry " + i + ": " + int16View[i]); } ``` 雖然該緩衝上已有一個 32 位元的視圖,這裡建立了同一個緩衝上的 16 位元整數視圖,這裡的輸出為 0, 0, 2, 0, 4, 0, 6, 0。 繼續考慮這種情況: ```js int16View[0] = 32; console.log("現在32位元陣列的欄位0是" + int32View[0]); ``` 輸出為"現在 32 位元陣列的欄位 0 是 32"。也就是,這兩個陣列真的是同一個資料緩衝的在不同格式下的看法。其他 view types 也是同樣的情形。 ### 處理複雜的資料結構 在單一個緩衝使用不同型別、不同起始偏移的多個視圖以操作資料物件含有的多個資料型別。這個方法可以用在使用 WebGL 、資料檔案、js-ctypes 時遇到的複雜的資料結構。 考慮這個 C 結構: ```cpp struct someStruct { unsigned long id; char username[16]; float amountDue; }; ``` 可以用以下方法存取含有這種資料格式的緩衝: ```js var buffer = new ArrayBuffer(24); // ... 將資料讀入緩衝 ... var idView = new Uint32Array(buffer, 0, 1); var usernameView = new Uint8Array(buffer, 4, 16); var amountDueView = new Float32Array(buffer, 20, 1); ``` 舉例來說,可以用 `amountDueView[0]` 存取 amountDue。 **備註:** C 結構的 data structure alignment 是與使用平台有關,須小心這些填充上的差異。 ### Conversion to normal arrays After processing a typed array, it is sometimes useful to convert it back to a normal array in order to benefit from the `Array` prototype. This can be done using `Array.from`, or using the following code where `Array.from` is unsupported. ```js var typedArray = new Uint8Array([1, 2, 3, 4]), normalArray = Array.prototype.slice.call(typedArray); normalArray.length === 4; normalArray.constructor === Array; ``` 參見 -- * Getting `ArrayBuffer`s or typed arrays from *Base64*-encoded strings (en-US) * `StringView` – a C-like representation of strings based on typed arrays * Faster Canvas Pixel Manipulation with Typed Arrays * Typed Arrays: Binary Data in the Browser * Endianness (en-US)
數字與日期 - JavaScript
數字與日期 ===== * « 前頁 * 次頁 » (en-US) 這個章節將介紹如何在 JavaScript 中處理數字與日期。 數字(Numbers) ----------- 在 JavaScript 中, Number 所使用的標準依照 double-precision 64-bit binary format IEEE 754 (i.e. number 的區間是 -(2^53 -1) 到 2^53 -1)。**整數是沒有特定的類型**。 此外還可以顯示浮點數,三種符號數值: `+``Infinity`, `-``Infinity`, and `NaN` (not-a-number)。 `BigInt` 是 Javascript 最新的功能,它可以表示一個很大的整數。使用 `BigInt需要注意一點`,`BigInt` 和`Number`不能在同一個 operation 混用還有當用 `Math` 物件時不能使用`BigInt`。 請參照 JavaScript data types and structures 來取得更多詳細資料。 你可以用四種進制表示數字:十進制 (decimal),二進制 (binary),八進制 (octal) 以及十六進制 (hexadecimal)。 ### 十進制數值 ```js 1234567890; 42; // 以零為開頭時要小心: 0888; // 888 解析為 十進制數值 0777; // 在 non-strict 模式下將解析成八進制 (等同於十進制的 511) ``` 請注意,十進位數字允許第一個數字設為零(`0`)的話,前提是後面接的數字必須要有一個數字大於 8(例如輸入 0888 結果會是 888,輸入 068 結果會是 68),不然則會被轉成8進位(例如 0777 結果會是 511,輸入 063 結果會是 51)。 ### 二進制數值 二進制數值以 0 為開頭並跟著一個大寫或小寫的英文字母 「B」 (`0b` 或 `0B`)。如果 `0b` 後面接著的數字不是 0 或 1,那會丟出 `SyntaxError(語法錯誤)` (en-US): "Missing binary digits after 0b"。 ```js var FLT\_SIGNBIT = 0b10000000000000000000000000000000; // 2147483648 var FLT\_EXPONENT = 0b01111111100000000000000000000000; // 2139095040 var FLT\_MANTISSA = 0b00000000011111111111111111111111; // 8388607 ``` ### 八進制數值 八進制數值以 0 為開頭。如果 `0` 後面的數字超出 0 到 7 這個範圍,將會被解析成十進制數值。 ```js var n = 0755; // 493 var m = 0644; // 420 ``` Strict mode in ECMAScript 5 forbids octal syntax. Octal syntax isn't part of ECMAScript 5, but it's supported in all browsers by prefixing the octal number with a zero: `0644 === 420` and`"\045" === "%"`. In ECMAScript 2015, octal numbers are supported if they are prefixed with `0o`, e.g.: ```js var a = 0o10; // ES2015: 8 ``` ### 十六進制數值 十六進制數值以 0 為開頭並跟著一個大寫或小寫的英文字母 「X」(`0x` 或 `0X`)。如果 `0b` 後面接著的值超出範圍 (0123456789ABCDEF),那會丟出 `SyntaxError(語法錯誤)` (en-US):"Identifier starts immediately after numeric literal"。 ```js 0xfffffffffffffffff; // 295147905179352830000 0x123456789abcdef; // 81985529216486900 0xa; // 10 ``` ### 指數運算 ```js 1e3; // 1000 2e6; // 2000000 0.1e2; // 10 ``` `Number` 物件 ----------- The built-in `Number` object has properties for numerical constants, such as maximum value, not-a-number, and infinity. You cannot change the values of these properties and you use them as follows: ```js var biggestNum = Number.MAX\_VALUE; var smallestNum = Number.MIN\_VALUE; var infiniteNum = Number.POSITIVE\_INFINITY; var negInfiniteNum = Number.NEGATIVE\_INFINITY; var notANum = Number.NaN; ``` You always refer to a property of the predefined `Number` object as shown above, and not as a property of a `Number` object you create yourself. 下面這張表格整理了 `Number` 物件的屬性 `Number` **的屬性** | 屬性 | 描述 | | --- | --- | | `Number.MAX_VALUE` (en-US) | 可表示的最大數值 | | `Number.MIN_VALUE` (en-US) | 可表示的最小數值 | | `Number.NaN` (en-US) | 表示「非數值」(Not-A-Number)的數值 | | `Number.NEGATIVE_INFINITY` (en-US) | Special negative infinite value; returned on overflow | | `Number.POSITIVE_INFINITY` (en-US) | Special positive infinite value; returned on overflow | | `Number.EPSILON` (en-US) | Difference between one and the smallest value greater than one that can be represented as a `Number`. | | `Number.MIN_SAFE_INTEGER` (en-US) | 可以在 JavaScript 中安全表示的最小數值。 | | `Number.MAX_SAFE_INTEGER` (en-US) | 可以在 JavaScript 中安全表示的最大數值。 | | 方法 | 描述 | | --- | --- | | `Number.parseFloat()` (en-US) | 字串轉換成浮點數。 等同於全域函式 `parseFloat()` (en-US) 。 | | `Number.parseInt()` (en-US) | 以指定的基數將字串轉換成整數。 等同於全域函式 `parseInt()` 。 | | `Number.isFinite()` (en-US) | 判定給定的值是不是一個有限數。 | | `Number.isInteger()` (en-US) | 判定給定的值是不是一個整數 | | `Number.isNaN()` (en-US) | Determines whether the passed value is `NaN`. More robust version of the original global `isNaN()`. | | `Number.isSafeInteger()` (en-US) | Determines whether the provided value is a number that is a *safe integer*. | The `Number` prototype provides methods for retrieving information from `Number` objects in various formats. The following table summarizes the methods of `Number.prototype`. | 方法 | 描述 | | --- | --- | | `toExponential()` | Returns a string representing the number in exponential notation. | | `toFixed()` | Returns a string representing the number in fixed-point notation. | | `toPrecision()` (en-US) | Returns a string representing the number to a specified precision in fixed-point notation. | `Math` 物件 --------- The built-in `Math` object has properties and methods for mathematical constants and functions. For example, the `Math` object's `PI` property has the value of pi (3.141...), which you would use in an application as ```js Math.PI; ``` Similarly, standard mathematical functions are methods of `Math`. These include trigonometric, logarithmic, exponential, and other functions. For example, if you want to use the trigonometric function sine, you would write ```js Math.sin(1.56); ``` Note that all trigonometric methods of `Math` take arguments in radians. The following table summarizes the `Math` object's methods. | 方法 | 描述 | | --- | --- | | `abs()` (en-US) | 絕對值 | | `sin()` (en-US), `cos()` (en-US), `tan()` (en-US) | 三角函數; 引數以弳度表示 | | `asin()` (en-US), `acos()` (en-US), `atan()` (en-US), `atan2()` (en-US) | 反三角函數; 回傳值以弳度表示 | | `sinh()` (en-US), `cosh()` (en-US), `tanh()` (en-US) | 雙曲函數; 引數以 hyperbolic angle 表示 | | `asinh()` (en-US), `acosh()` (en-US), `atanh()` (en-US) | 反雙曲函數; 回傳值以 hyperbolic angle 表示 | | `pow()` (en-US), `exp()` (en-US), `expm1()` (en-US), `log10()` (en-US), `log1p()` (en-US), `log2()` (en-US) | 指數及對數函式 | | `floor()`, `ceil()` | 回傳小於等於/大於等於指定數字的最大/最小整數 | | `min()` (en-US), `max()` (en-US) | Returns lesser or greater (respectively) of comma separated list of numbers arguments | | `random()` | 回傳一個介於 0 到 1 之間的數值 | | `round()`, `fround()` (en-US), `trunc()` (en-US), | Rounding and truncation functions. | | `sqrt()` (en-US), `cbrt()` (en-US), `hypot()` (en-US) | Square root, cube root, Square root of the sum of square arguments. | | `sign()` (en-US) | The sign of a number, indicating whether the number is positive, negative or zero. | | `clz32()` (en-US), `imul()` (en-US) | Number of leading zero bits in the 32-bit binary representation. The result of the C-like 32-bit multiplication of the two arguments. | Unlike many other objects, you never create a `Math` object of your own. You always use the built-in `Math` object. `Date` 物件 --------- JavaScript 沒有所謂日期(date)的數據型態(data type)。你可以使用 `Date` 物件及其方法去設定日期跟時間來滿足你的需求 。`Date` 物件有大量的設定取得操作日期的方法(method),但它沒有屬性。 JavaScript 處理日期的方式跟 Java 類似。這兩個語言有許多一樣的 date 方法,且都將日期儲存為從 1970 年 1 月 1 號 0 時 0 分 0 秒以來的毫秒數(millisecond)。 `Date` 物件範圍是 -100,000,000 days to 100,000,000 days 以 1970 年 1 月 1 號 0 時 0 分 0 秒 UTC 為基準。 創建一個`Date`物件: ```js var dateObjectName = new Date([parameters]); ``` 在這裡創建一個名為`dateObjectName` 的 `Date` 物件;它可以是一個新的物件或是某個以存在的物件當中的屬性。 Calling `Date` without the `new` keyword returns a string representing the current date and time. The `parameters` in the preceding syntax can be any of the following: * Nothing: creates today's date and time. For example, `today = new Date();`. * A string representing a date in the following form: "Month day, year hours:minutes:seconds." For example, `var Xmas95 = new Date("December 25, 1995 13:30:00")`. If you omit hours, minutes, or seconds, the value will be set to zero. * A set of integer values for year, month, and day. For example, `var Xmas95 = new Date(1995, 11, 25)`. * A set of integer values for year, month, day, hour, minute, and seconds. For example, `var Xmas95 = new Date(1995, 11, 25, 9, 30, 0);`. ### `Date` 的方法 The `Date` object methods for handling dates and times fall into these broad categories: * "set" methods, for setting date and time values in `Date` objects. * "get" methods, for getting date and time values from `Date` objects. * "to" methods, for returning string values from `Date` objects. * parse and UTC methods, for parsing `Date` strings. With the "get" and "set" methods you can get and set seconds, minutes, hours, day of the month, day of the week, months, and years separately. There is a `getDay` method that returns the day of the week, but no corresponding `setDay` method, because the day of the week is set automatically. These methods use integers to represent these values as follows: * Seconds and minutes: 0 到 59 * Hours: 0 到 23 * Day: 0 (星期日) 到 6 (星期六) * Date: 1 到 31 (這個月的第幾天) * Months: 0 (一月) 到 11 (十二月) * Year: years since 1900 舉例,假設你定義了一個日期如下: ```js var Xmas95 = new Date("December 25, 1995"); ``` 那 `Xmas95.getMonth()` 將會回傳 11, `Xmas95.getFullYear()` 會回傳 1995。 `getTime` 及 `setTime` 這兩個方法對於比較日期有幫助。 The `getTime` method returns the number of milliseconds since January 1, 1970, 00:00:00 for a `Date` object. For example, the following code displays the number of days left in the current year: ```js var today = new Date(); var endYear = new Date(1995, 11, 31, 23, 59, 59, 999); // Set day and month endYear.setFullYear(today.getFullYear()); // Set year to this year var msPerDay = 24 \* 60 \* 60 \* 1000; // Number of milliseconds per day var daysLeft = (endYear.getTime() - today.getTime()) / msPerDay; var daysLeft = Math.round(daysLeft); //returns days left in the year ``` This example creates a `Date` object named `today` that contains today's date. It then creates a `Date` object named `endYear` and sets the year to the current year. Then, using the number of milliseconds per day, it computes the number of days between `today` and `endYear`, using `getTime` and rounding to a whole number of days. The `parse` method is useful for assigning values from date strings to existing `Date` objects. For example, the following code uses `parse` and `setTime` to assign a date value to the `IPOdate` object: ```js var IPOdate = new Date(); IPOdate.setTime(Date.parse("Aug 9, 1995")); ``` ### 範例 下面這個範例,`JSClock()` 這個函式將會以數位時鐘的格式回傳時間。 ```js function JSClock() { var time = new Date(); var hour = time.getHours(); var minute = time.getMinutes(); var second = time.getSeconds(); var temp = "" + (hour > 12 ? hour - 12 : hour); if (hour == 0) temp = "12"; temp += (minute < 10 ? ":0" : ":") + minute; temp += (second < 10 ? ":0" : ":") + second; temp += hour >= 12 ? " P.M." : " A.M."; return temp; } ``` `JSClock` 這個函式會先建立一個名為 `time` 的 `Date` 物件; 因為沒有提供任何引數,所以會放入目前的日期及時間。接著呼叫 `getHours` 、 `getMinutes` 以及 `getSeconds` 這三個方法將現在的時、分以及秒分別指定給 `hour` 、 `minute` 以及 `second` 這三個變數。 接著的四行指令將會建立一個時間的字串。第一行的指令建立了一個變數 `temp`,以條件運算式指定值; 如果 `hour` 大於 12,那就指定 (`hour - 12`),不然會直接指定 `hour`, 但如果 `hour` 等於 0 , 則改為 12。 接著下一行將 `minute` 加到 `temp` 中。如果 `minute` 小於 10, 則會在附加時補上一個零; 不然的話會直接加上冒號及分鐘數。秒數也是以同樣的作法附加到 `temp` 上。 最後,判斷 `hour` 是不是大於等於 12 ,如果是就在 `temp` 加上 "P.M." ,不然就加上 "A.M."。 * « 前頁 * 次頁 » (en-US)