From 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:43:23 -0500 Subject: initial commit --- .../global_objects/array/@@iterator/index.html | 89 ++++ .../global_objects/array/concat/index.html | 157 +++++++ .../global_objects/array/copywithin/index.html | 156 +++++++ .../global_objects/array/entries/index.html | 86 ++++ .../global_objects/array/every/index.html | 191 +++++++++ .../reference/global_objects/array/fill/index.html | 156 +++++++ .../global_objects/array/filter/index.html | 238 +++++++++++ .../reference/global_objects/array/find/index.html | 204 +++++++++ .../global_objects/array/findindex/index.html | 181 ++++++++ .../reference/global_objects/array/flat/index.html | 148 +++++++ .../global_objects/array/foreach/index.html | 297 +++++++++++++ .../reference/global_objects/array/from/index.html | 215 ++++++++++ .../global_objects/array/includes/index.html | 175 ++++++++ .../reference/global_objects/array/index.html | 457 ++++++++++++++++++++ .../global_objects/array/indexof/index.html | 260 ++++++++++++ .../global_objects/array/isarray/index.html | 134 ++++++ .../reference/global_objects/array/join/index.html | 109 +++++ .../reference/global_objects/array/keys/index.html | 76 ++++ .../global_objects/array/lastindexof/index.html | 168 ++++++++ .../global_objects/array/length/index.html | 131 ++++++ .../reference/global_objects/array/map/index.html | 320 ++++++++++++++ .../reference/global_objects/array/of/index.html | 98 +++++ .../reference/global_objects/array/pop/index.html | 98 +++++ .../reference/global_objects/array/push/index.html | 143 +++++++ .../global_objects/array/reduce/index.html | 472 +++++++++++++++++++++ .../global_objects/array/reverse/index.html | 90 ++++ .../global_objects/array/shift/index.html | 114 +++++ .../global_objects/array/slice/index.html | 242 +++++++++++ .../reference/global_objects/array/some/index.html | 217 ++++++++++ .../reference/global_objects/array/sort/index.html | 248 +++++++++++ .../global_objects/array/splice/index.html | 150 +++++++ .../global_objects/array/unshift/index.html | 101 +++++ .../global_objects/array/values/index.html | 77 ++++ .../global_objects/arraybuffer/index.html | 225 ++++++++++ .../arraybuffer/prototype/index.html | 110 +++++ .../global_objects/asyncfunction/index.html | 118 ++++++ .../reference/global_objects/bigint/index.html | 279 ++++++++++++ .../reference/global_objects/boolean/index.html | 199 +++++++++ .../reference/global_objects/dataview/index.html | 173 ++++++++ .../global_objects/date/getday/index.html | 72 ++++ .../reference/global_objects/date/index.html | 263 ++++++++++++ .../reference/global_objects/date/now/index.html | 123 ++++++ .../global_objects/date/prototype/index.html | 245 +++++++++++ .../reference/global_objects/date/utc/index.html | 157 +++++++ .../global_objects/error/columnnumber/index.html | 81 ++++ .../reference/global_objects/error/index.html | 233 ++++++++++ .../global_objects/function/apply/index.html | 260 ++++++++++++ .../global_objects/function/bind/index.html | 321 ++++++++++++++ .../global_objects/function/call/index.html | 105 +++++ .../reference/global_objects/function/index.html | 191 +++++++++ .../global_objects/function/length/index.html | 144 +++++++ .../global_objects/function/prototype/index.html | 138 ++++++ .../javascript/reference/global_objects/index.html | 201 +++++++++ .../reference/global_objects/infinity/index.html | 76 ++++ .../reference/global_objects/isnan/index.html | 183 ++++++++ .../reference/global_objects/json/index.html | 206 +++++++++ .../reference/global_objects/json/parse/index.html | 170 ++++++++ .../global_objects/json/stringify/index.html | 280 ++++++++++++ .../reference/global_objects/map/index.html | 265 ++++++++++++ .../reference/global_objects/math/abs/index.html | 104 +++++ .../reference/global_objects/math/ceil/index.html | 170 ++++++++ .../reference/global_objects/math/floor/index.html | 169 ++++++++ .../reference/global_objects/math/index.html | 196 +++++++++ .../reference/global_objects/math/max/index.html | 117 +++++ .../reference/global_objects/math/pow/index.html | 107 +++++ .../global_objects/math/random/index.html | 95 +++++ .../reference/global_objects/math/round/index.html | 212 +++++++++ .../reference/global_objects/nan/index.html | 85 ++++ .../reference/global_objects/null/index.html | 124 ++++++ .../reference/global_objects/number/index.html | 219 ++++++++++ .../global_objects/number/isfinite/index.html | 93 ++++ .../global_objects/number/isnan/index.html | 99 +++++ .../global_objects/number/prototype/index.html | 84 ++++ .../global_objects/number/toexponential/index.html | 164 +++++++ .../global_objects/number/tofixed/index.html | 108 +++++ .../global_objects/object/assign/index.html | 249 +++++++++++ .../global_objects/object/create/index.html | 258 +++++++++++ .../object/defineproperties/index.html | 224 ++++++++++ .../object/defineproperty/index.html | 380 +++++++++++++++++ .../global_objects/object/freeze/index.html | 198 +++++++++ .../object/getprototypeof/index.html | 128 ++++++ .../object/hasownproperty/index.html | 184 ++++++++ .../reference/global_objects/object/index.html | 222 ++++++++++ .../global_objects/object/keys/index.html | 208 +++++++++ .../object/preventextensions/index.html | 179 ++++++++ .../global_objects/object/proto/index.html | 137 ++++++ .../global_objects/object/prototype/index.html | 218 ++++++++++ .../global_objects/object/watch/index.html | 191 +++++++++ .../reference/global_objects/parseint/index.html | 193 +++++++++ .../global_objects/promise/all/index.html | 207 +++++++++ .../global_objects/promise/catch/index.html | 189 +++++++++ .../global_objects/promise/finally/index.html | 102 +++++ .../reference/global_objects/promise/index.html | 256 +++++++++++ .../global_objects/promise/prototype/index.html | 64 +++ .../global_objects/promise/race/index.html | 171 ++++++++ .../global_objects/promise/reject/index.html | 72 ++++ .../global_objects/promise/resolve/index.html | 142 +++++++ .../global_objects/promise/then/index.html | 271 ++++++++++++ .../reference/global_objects/proxy/index.html | 400 +++++++++++++++++ .../reference/global_objects/rangeerror/index.html | 152 +++++++ .../reference/global_objects/reflect/index.html | 130 ++++++ .../reference/global_objects/regexp/index.html | 269 ++++++++++++ .../reference/global_objects/set/add/index.html | 83 ++++ .../reference/global_objects/set/clear/index.html | 79 ++++ .../reference/global_objects/set/delete/index.html | 98 +++++ .../global_objects/set/entries/index.html | 78 ++++ .../reference/global_objects/set/has/index.html | 92 ++++ .../reference/global_objects/set/index.html | 243 +++++++++++ .../reference/global_objects/set/values/index.html | 79 ++++ .../reference/global_objects/string/index.html | 328 ++++++++++++++ .../global_objects/string/match/index.html | 151 +++++++ .../global_objects/string/padstart/index.html | 96 +++++ .../global_objects/string/prototype/index.html | 176 ++++++++ .../global_objects/string/replace/index.html | 286 +++++++++++++ .../global_objects/string/tolowercase/index.html | 77 ++++ .../reference/global_objects/typedarray/index.html | 268 ++++++++++++ .../reference/global_objects/undefined/index.html | 136 ++++++ .../reference/global_objects/urierror/index.html | 131 ++++++ 118 files changed, 20757 insertions(+) create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/@@iterator/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/concat/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/copywithin/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/entries/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/every/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/fill/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/filter/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/find/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/findindex/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/flat/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/foreach/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/from/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/includes/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/indexof/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/isarray/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/join/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/keys/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/lastindexof/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/length/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/map/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/of/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/pop/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/push/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/reduce/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/reverse/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/shift/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/slice/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/some/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/sort/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/splice/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/unshift/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/array/values/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/arraybuffer/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/arraybuffer/prototype/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/asyncfunction/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/bigint/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/boolean/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/dataview/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/date/getday/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/date/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/date/now/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/date/prototype/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/date/utc/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/error/columnnumber/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/error/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/function/apply/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/function/bind/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/function/call/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/function/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/function/length/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/function/prototype/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/infinity/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/isnan/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/json/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/json/parse/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/json/stringify/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/map/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/math/abs/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/math/ceil/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/math/floor/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/math/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/math/max/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/math/pow/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/math/random/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/math/round/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/nan/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/null/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/number/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/number/isfinite/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/number/isnan/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/number/prototype/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/number/toexponential/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/number/tofixed/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/assign/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/create/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/defineproperties/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/defineproperty/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/freeze/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/getprototypeof/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/hasownproperty/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/keys/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/preventextensions/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/proto/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/prototype/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/object/watch/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/parseint/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/promise/all/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/promise/catch/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/promise/finally/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/promise/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/promise/prototype/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/promise/race/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/promise/reject/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/promise/resolve/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/promise/then/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/proxy/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/rangeerror/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/reflect/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/regexp/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/set/add/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/set/clear/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/set/delete/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/set/entries/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/set/has/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/set/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/set/values/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/string/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/string/match/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/string/padstart/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/string/prototype/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/string/replace/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/string/tolowercase/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/typedarray/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/undefined/index.html create mode 100644 files/zh-tw/web/javascript/reference/global_objects/urierror/index.html (limited to 'files/zh-tw/web/javascript/reference/global_objects') diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/@@iterator/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/@@iterator/index.html new file mode 100644 index 0000000000..eb73724bef --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/@@iterator/index.html @@ -0,0 +1,89 @@ +--- +title: 'Array.prototype[@@iterator]()' +slug: Web/JavaScript/Reference/Global_Objects/Array/@@iterator +tags: + - Array + - ECMAScript 2015 + - Iterator + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/@@iterator +--- +
{{JSRef}}
+ +

@@iterator 屬性的初始值與 {{jsxref("Array.prototype.values()", "values()")}} 屬性的初始值為相同的的函式物件。

+ +

語法

+ +
arr[Symbol.iterator]()
+ +

回傳值

+ +

陣列的迭代器(iterator)函式,預設與 {{jsxref("Array.prototype.values()", "values()")}} 函式相同。

+ +

範例

+ +

使用 for...of 迴圈進行迭代

+ +
var arr = ['w', 'y', 'k', 'o', 'p'];
+var eArr = arr[Symbol.iterator]();
+// your browser must support for..of loop
+// and let-scoped variables in for loops
+for (let letter of eArr) {
+  console.log(letter);
+}
+
+ +

另一種迭代方式

+ +
var arr = ['w', 'y', 'k', 'o', 'p'];
+var eArr = arr[Symbol.iterator]();
+console.log(eArr.next().value); // w
+console.log(eArr.next().value); // y
+console.log(eArr.next().value); // k
+console.log(eArr.next().value); // o
+console.log(eArr.next().value); // p
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-array.prototype-@@iterator', 'Array.prototype[@@iterator]()')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype-@@iterator', 'Array.prototype[@@iterator]()')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.@@iterator")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/concat/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/concat/index.html new file mode 100644 index 0000000000..c8fc9a7aca --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/concat/index.html @@ -0,0 +1,157 @@ +--- +title: Array.prototype.concat() +slug: Web/JavaScript/Reference/Global_Objects/Array/concat +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference + - 陣列 +translation_of: Web/JavaScript/Reference/Global_Objects/Array/concat +--- +
{{JSRef}}
+ +

concat() 方法被用來合併兩個或多個陣列。此方法不會改變現有的陣列,回傳一個包含呼叫者陣列本身的值,作為代替的是回傳一個新陣列。

+ +
{{EmbedInteractiveExample("pages/js/array-concat.html")}}
+ + + +

語法

+ +
var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])
+ +

參數

+ +
+
valueN
+
陣列以及/或者值,用來合併成一個新的陣列。請參閱下方詳細資訊描述。
+
+ +

回傳值

+ +

一個新的{{jsxref("Array","陣列")}}實體。

+ +

描述

+ +

concat 產生一個由呼叫者陣列自己的元素,以及對每一個參數按照順序,合併參數的元素(如果參數是個陣列)或者是參數自己本身(如果參數不是一個陣列)成為一個新的陣列。concat 方法不會遞迴巢狀陣列參數。

+ +

concat 方法不會改變 this 自己本身或是任何被提供當做參數的陣列,取而代之則是回傳一個淺層複製(shallow copy)包含了與原始的陣列中一樣的元素的副本。原始陣列的元素被複製到新的陣列的規則如下所示:

+ + + +
+

備註:合併(多個)陣列/(多個)值將讓原始的陣列不會被受到影響。此外,任何對新陣列(只有在元素不是物件參考的情況下)的操作都不會影響原始的陣列,反之亦然。

+
+ +

範例

+ +

合併兩個陣列

+ +

下面的程式碼為合併兩個陣列:

+ +
var alpha = ['a', 'b', 'c'];
+var numeric = [1, 2, 3];
+
+alpha.concat(numeric);
+// 結果: ['a', 'b', 'c', 1, 2, 3]
+
+ +

合併三個陣列

+ +

下面的程式碼為合併三個陣列:

+ +
var num1 = [1, 2, 3],
+    num2 = [4, 5, 6],
+    num3 = [7, 8, 9];
+
+var nums = num1.concat(num2, num3);
+
+console.log(nums);
+// 結果:[1, 2, 3, 4, 5, 6, 7, 8, 9]
+
+ +

合併值到一個陣列

+ +

下面的程式碼為合併三個值到一個陣列中:

+ +
var alpha = ['a', 'b', 'c'];
+
+var alphaNumeric = alpha.concat(1, [2, 3]);
+
+console.log(alphaNumeric);
+// 結果:['a', 'b', 'c', 1, 2, 3]
+
+ +

合併巢狀陣列

+ +

下面的程式碼為合併巢狀陣列,並證明保留了原本的參考(references):

+ +
var num1 = [[1]];
+var num2 = [2, [3]];
+
+var nums = num1.concat(num2);
+
+console.log(nums);
+// results in [[1], 2, [3]]
+
+// modify the first element of num1
+num1[0].push(4);
+
+console.log(nums);
+// results in [[1, 4], 2, [3]]
+
+ +

規格

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
規格狀態備註
{{SpecName('ES3')}}{{Spec2('ES3')}}首次定義。實作於 JavaScript 1.2。
{{SpecName('ES5.1', '#sec-15.4.4.4', 'Array.prototype.concat')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.concat', 'Array.prototype.concat')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.concat', 'Array.prototype.concat')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.concat")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/copywithin/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/copywithin/index.html new file mode 100644 index 0000000000..30520215e3 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/copywithin/index.html @@ -0,0 +1,156 @@ +--- +title: Array.prototype.copyWithin() +slug: Web/JavaScript/Reference/Global_Objects/Array/copyWithin +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/copyWithin +--- +
{{JSRef}}
+ +

copyWithin() 方法會對陣列的一部分進行淺拷貝至同一陣列的另一位置並回傳此陣列,而不修改其大小。

+ +
{{EmbedInteractiveExample("pages/js/array-copywithin.html")}}
+ + + +

語法

+ +
arr.copyWithin(target)
+arr.copyWithin(target, start)
+arr.copyWithin(target, start, end)
+
+ +

參數

+ +
+
target
+
要複製序列(sequence)至該位置的索引(起始為 0)。若為負數,target 將會自陣列末項開始計算。
+
假如 target 大於等於 arr.length,則沒有項目會被複製。如果 target 的索引在 start 之後,則拷貝的序列將會被修剪以符合 arr.length
+
start {{optional_inline}}
+
開始拷貝的起始元素索引(起始為 0)。若為負數,start 將會自陣列末項開始計算。
+
如果省略 startcopyWithin 將會自陣列首項開始複製(預設為 0)。
+
end {{optional_inline}}
+
結束拷貝的結尾元素索引(起始為 0)。copyWithin 會拷貝至此索引,但不包含 end。若為負數,end 將會自陣列末項開始計算。
+
如果省略 endcopyWithin 將會一路拷貝至陣列末項(預設至 arr.length)。
+
+ +

回傳值

+ +

被修改後的陣列。

+ +

描述

+ +

The copyWithin works like C and C++'s memmove, and is a high-performance method to shift the data of an {{jsxref("Array")}}. This especially applies to the {{jsxref("TypedArray/copyWithin", "TypedArray")}} 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 {{jsxref("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.

+ +

範例

+ +
[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

+ +
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);
+  }
+}
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-array.prototype.copywithin', 'Array.prototype.copyWithin')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ES2016', '#sec-array.prototype.copywithin', 'Array.prototype.copyWithin')}}{{Spec2('ES2016')}} 
{{SpecName('ESDraft', '#sec-array.prototype.copywithin', 'Array.prototype.copyWithin')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.copyWithin")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/entries/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/entries/index.html new file mode 100644 index 0000000000..80c3f33e1f --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/entries/index.html @@ -0,0 +1,86 @@ +--- +title: Array.prototype.entries() +slug: Web/JavaScript/Reference/Global_Objects/Array/entries +tags: + - Array + - ECMAScript6 + - Iterator + - JavaScript + - Method + - Prototype + - 迭代器 + - 陣列 +translation_of: Web/JavaScript/Reference/Global_Objects/Array/entries +--- +
{{JSRef}}
+ +

entries() 方法會回傳一個包含陣列中每一個索引之鍵值對(key/value pairs)的新陣列迭代器(Array Iterator)物件。

+ +
{{EmbedInteractiveExample("pages/js/array-entries.html")}}
+ + + +

語法

+ +
a.entries()
+ +

回傳值

+ +

一個新的 {{jsxref("Array")}} 迭代器物件。

+ +

範例

+ +

使用 for…of 進行迭代

+ +
var a = ['a', 'b', 'c'];
+var iterator = a.entries();
+
+for (let e of iterator) {
+  console.log(e);
+}
+// [0, 'a']
+// [1, 'b']
+// [2, 'c']
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
規格狀態備註
{{SpecName('ES2015', '#sec-array.prototype.entries', 'Array.prototype.entries')}}{{Spec2('ES2015')}}首次定義。
{{SpecName('ESDraft', '#sec-array.prototype.entries', 'Array.prototype.entries')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.entries")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/every/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/every/index.html new file mode 100644 index 0000000000..3c0aa59938 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/every/index.html @@ -0,0 +1,191 @@ +--- +title: Array.prototype.every() +slug: Web/JavaScript/Reference/Global_Objects/Array/every +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/every +--- +
{{JSRef}}
+ +

every() 方法會測試陣列中的所有元素是否都通過了由給定之函式所實作的測試。

+ +
{{EmbedInteractiveExample("pages/js/array-every.html")}}
+ + + +

語法

+ +
arr.every(callback[, thisArg])
+ +

參數

+ +
+
callback
+
用來測試每一個元素的函式,它包含三個引數: +
+
currentValue(必要的)
+
目前正要被處理的陣列元素。
+
index(可選的)
+
目前正要被處理的陣列元素之索引值。
+
array(可選的)
+
呼叫 every 的陣列。
+
+
+
thisArg
+
可選的。執行 callback 回呼函式的 this 值。
+
+ +

回傳值

+ +

若回呼函式在處理每一個陣列元素時皆得到 {{Glossary("truthy")}} 值,則回傳 true。否則,回傳值為 false

+ +

描述

+ +

The every method executes the provided callback function once for each element present in the array until it finds one where callback returns a {{Glossary("falsy")}} value. If such an element is found, the every method immediately returns false. Otherwise, if callback returns a {{Glossary("truthy")}} value for all elements, every returns true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.

+ +

callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.

+ +

If a thisArg parameter is provided to every, it will be used as callback's this value. Otherwise, the value undefined will be used as its this value.  The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.

+ +

every does not mutate the array on which it is called.

+ +

The range of elements processed by every is set before the first invocation of callback. Elements which are appended to the array after the call to every begins will not be visited by callback. If existing elements of the array are changed, their value as passed to callback will be the value at the time every visits them; elements that are deleted are not visited.

+ +

every acts like the "for all" quantifier in mathematics. In particular, for an empty array, it returns true. (It is vacuously true that all elements of the empty set satisfy any given condition.)

+ +

範例

+ +

Testing size of all array elements

+ +

The following example tests whether all elements in the array are bigger than 10.

+ +
function isBigEnough(element, index, array) {
+  return element >= 10;
+}
+[12, 5, 8, 130, 44].every(isBigEnough);   // false
+[12, 54, 18, 130, 44].every(isBigEnough); // true
+
+ +

Using arrow functions

+ +

Arrow functions provide a shorter syntax for the same test.

+ +
[12, 5, 8, 130, 44].every(x => x >= 10); // false
+[12, 54, 18, 130, 44].every(x => x >= 10); // true
+ +

Polyfill

+ +

every 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 every in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming Object and TypeError have their original values and that callbackfn.call evaluates to the original value of {{jsxref("Function.prototype.call")}}

+ +
if (!Array.prototype.every) {
+  Array.prototype.every = function(callbackfn, thisArg) {
+    'use strict';
+    var T, k;
+
+    if (this == null) {
+      throw new TypeError('this is null or not defined');
+    }
+
+    // 1. Let O be the result of calling ToObject passing the this
+    //    value as the argument.
+    var O = Object(this);
+
+    // 2. Let lenValue be the result of calling the Get internal method
+    //    of O with the argument "length".
+    // 3. Let len be ToUint32(lenValue).
+    var len = O.length >>> 0;
+
+    // 4. If IsCallable(callbackfn) is false, throw a TypeError exception.
+    if (typeof callbackfn !== 'function') {
+      throw new TypeError();
+    }
+
+    // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
+    if (arguments.length > 1) {
+      T = thisArg;
+    }
+
+    // 6. Let k be 0.
+    k = 0;
+
+    // 7. Repeat, while k < len
+    while (k < len) {
+
+      var kValue;
+
+      // a. Let Pk be ToString(k).
+      //   This is implicit for LHS operands of the in operator
+      // b. Let kPresent be the result of calling the HasProperty internal
+      //    method of O with argument Pk.
+      //   This step can be combined with c
+      // c. If kPresent is true, then
+      if (k in O) {
+
+        // i. Let kValue be the result of calling the Get internal method
+        //    of O with argument Pk.
+        kValue = O[k];
+
+        // ii. Let testResult be the result of calling the Call internal method
+        //     of callbackfn with T as the this value and argument list
+        //     containing kValue, k, and O.
+        var testResult = callbackfn.call(T, kValue, k, O);
+
+        // iii. If ToBoolean(testResult) is false, return false.
+        if (!testResult) {
+          return false;
+        }
+      }
+      k++;
+    }
+    return true;
+  };
+}
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.16', 'Array.prototype.every')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.every', 'Array.prototype.every')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.every', 'Array.prototype.every')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.every")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/fill/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/fill/index.html new file mode 100644 index 0000000000..1a7d0f9f24 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/fill/index.html @@ -0,0 +1,156 @@ +--- +title: Array.prototype.fill() +slug: Web/JavaScript/Reference/Global_Objects/Array/fill +tags: + - Array + - ECMAScript 2015 + - JavaScript + - 原型 + - 填充工具 + - 方法 +translation_of: Web/JavaScript/Reference/Global_Objects/Array/fill +--- +
{{JSRef}}
+ +

fill() 方法會將陣列中索引的第一個到最後一個的每個位置全部填入一個靜態的值。

+ +
{{EmbedInteractiveExample("pages/js/array-fill.html")}}
+ + + +

語法

+ +
arr.fill(value[, start[, end]])
+
+ +

參數

+ +
+
value
+
欲填入陣列的值。
+
start {{optional_inline}}
+
起始的索引值,預設為 0。
+
end {{optional_inline}}
+
結束的索引值,預設為 this.length(即陣列的長度)。
+
+ +

回傳值

+ +

修改後的陣列。

+ +

說明

+ +

要填入的元素區間為 [start, end),意即包含 start 但不包含 end

+ +

fill 方法採用了三個傳入引數(arguments),分別為valuestartendstartend 為可選引數,其預設值分別為 0this 物件(該陣列)的 length

+ +

start 為負數,則此方法會將其換算成 length+startlength 即該陣列的長度。同理,若 end 為負數,其會被換算成 length+end

+ +

fill 函式刻意地被設計成通用的函式,它不需要 this 物件一定是一個陣列物件。此外,它是可變動的(mutable)方法,意即會修改 this 物件本身並回傳,而非只是回傳拷貝。

+ +

當 fill 方法獲得一個傳入的物件,會將傳入的物件位置進行複製,並把其參考值(reference)之拷貝填入陣列中。

+ +

範例

+ +
[1, 2, 3].fill(4);               // [4, 4, 4]
+[1, 2, 3].fill(4, 1);            // [1, 4, 4]
+[1, 2, 3].fill(4, 1, 2);         // [1, 4, 3]
+[1, 2, 3].fill(4, 1, 1);         // [1, 2, 3]
+[1, 2, 3].fill(4, 3, 3);         // [1, 2, 3]
+[1, 2, 3].fill(4, -3, -2);       // [4, 2, 3]
+[1, 2, 3].fill(4, NaN, NaN);     // [1, 2, 3]
+[1, 2, 3].fill(4, 3, 5);         // [1, 2, 3]
+Array(3).fill(4);                // [4, 4, 4]
+[].fill.call({ length: 3 }, 4);  // {0: 4, 1: 4, 2: 4, length: 3}
+
+// Objects by reference.
+var arr = Array(3).fill({}) // [{}, {}, {}];
+arr[0].hi = "hi"; // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }]
+
+ +

Polyfill

+ +
if (!Array.prototype.fill) {
+  Object.defineProperty(Array.prototype, 'fill', {
+    value: function(value) {
+
+      // 步驟 1 - 2。
+       if (this == null) {
+        throw new TypeError('this is null or not defined');
+      }
+
+      var O = Object(this);
+
+      // 步驟 3 - 5。
+      var len = O.length >>> 0;
+
+      // 步驟 6 - 7。
+      var start = arguments[1];
+      var relativeStart = start >> 0;
+
+      // 步驟 8。
+      var k = relativeStart < 0 ?
+        Math.max(len + relativeStart, 0) :
+        Math.min(relativeStart, len);
+
+      // 步驟 9 - 10。
+      var end = arguments[2];
+      var relativeEnd = end === undefined ?
+        len : end >> 0;
+
+      // 步驟 11。
+      var final = relativeEnd < 0 ?
+        Math.max(len + relativeEnd, 0) :
+        Math.min(relativeEnd, len);
+
+      // 步驟 12。
+      while (k < final) {
+        O[k] = value;
+        k++;
+      }
+
+      // 步驟 13。
+      return O;
+    }
+  });
+}
+
+ +

如果你需要支援實際上棄用的 JavaScript 引擎且其不支援 Object.defineProperty 的話,最好不要採用上述的工具來填充方法至 Array.prototype,因為你不能將這個方法設定為不可列舉(non-enumerable)的屬性。

+ +

規範

+ + + + + + + + + + + + + + + + + + + +
規範狀態備註
{{SpecName('ES2015', '#sec-array.prototype.fill', 'Array.prototype.fill')}}{{Spec2('ES2015')}}初次定義。
{{SpecName('ESDraft', '#sec-array.prototype.fill', 'Array.prototype.fill')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.fill")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/filter/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/filter/index.html new file mode 100644 index 0000000000..49546e6505 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/filter/index.html @@ -0,0 +1,238 @@ +--- +title: Array.prototype.filter() +slug: Web/JavaScript/Reference/Global_Objects/Array/filter +tags: + - Array + - ECMAScript 5 + - JavaScript + - 原型 + - 參見 + - 填充工具 + - 方法 +translation_of: Web/JavaScript/Reference/Global_Objects/Array/filter +--- +
{{JSRef}}
+ +

filter() 方法會建立一個經指定之函式運算後,由原陣列中通過該函式檢驗之元素所構成的新陣列。

+ +
{{EmbedInteractiveExample("pages/js/array-filter.html")}}
+ + + +

ES6 版本

+ +
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{{optional_inline}}
+
原陣列目前所迭代處理中的元素之索引。
+
array{{optional_inline}}
+
呼叫 filter 方法的陣列。
+
+
+
thisArg {{optional_inline}}
+
可選的。執行 callback 回呼函式的 this 值。
+
+ +

回傳值

+ +

一個元素為通過回呼函式檢驗的新陣列。

+ +

描述

+ +

filter() 會將所有陣列中的元素分別傳入一次至 callback 函式當中,並將所有傳入此回呼函式並得到回傳值為 Truthy 的元素建構成一個新的陣列。callback 函式只會於陣列目前迭代之索引有指派值時被呼叫,回呼函式不會在該陣列索引已被刪除或從未被賦值時被調用。原始陣列中沒有通過 callback 檢驗的元素會被簡單的跳過,且不會被包含在新建立的陣列中。

+ +

callback 函式於被調用時會傳入三個參數:

+ +
    +
  1. 元素值
  2. +
  3. 元素之索引
  4. +
  5. 被迭代的陣列物件
  6. +
+ +

若有提供 thisArg 參數予 filter 方法,thisArg 將會被當作回呼函式的 this 值,否則 this 會是 undefinedcallback 的最終 this 值是依據函式的 this 規則來決定。

+ +

filter() 不會修改呼叫它的原始陣列。

+ +

filter() 方法所回傳之新陣列的範圍,於 callback 函式第一次被調用之前就已經被設定。而在呼叫 filter() 之後才加至原始陣列中的元素,將不會傳入 callback 當中。假如原始陣列中元素的值改變或被刪除了,則 callback 得到此元素的值將會是 filter() 傳入元素當下的值。而被刪除的原始陣列元素並不會被迭代到。

+ +

範例

+ +

過濾所有的小數字

+ +

以下範例會用 filter() 建立一個把所有小於 10 的元素都移掉的陣列。

+ +
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。

+ +
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() 去過濾符合搜尋條件的陣列內容。

+ +
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 實作方式

+ +
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 是採用 {{jsxref("Function.prototype.bind()")}} 的原始值,這個演算法完全和 ECMA-262 第五版定義的規格相同。

+ +
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;
+  };
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態備註
{{SpecName('ES5.1', '#sec-15.4.4.20', 'Array.prototype.filter')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.6.
{{SpecName('ES2015', '#sec-array.prototype.filter', 'Array.prototype.filter')}}{{Spec2('ES2015')}} 
{{SpecName('ESDraft', '#sec-array.prototype.filter', 'Array.prototype.filter')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.filter")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/find/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/find/index.html new file mode 100644 index 0000000000..0db7e05a3c --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/find/index.html @@ -0,0 +1,204 @@ +--- +title: Array.prototype.find() +slug: Web/JavaScript/Reference/Global_Objects/Array/find +translation_of: Web/JavaScript/Reference/Global_Objects/Array/find +--- +
{{JSRef}}
+ +

find() 方法會回傳第一個滿足所提供之測試函式的元素。否則回傳 {{jsxref("undefined")}}。

+ +
{{EmbedInteractiveExample("pages/js/array-find.html")}}
+ + + +

也可以參考 {{jsxref("Array.findIndex", "findIndex()")}} 方法,它回傳被找到的元素在陣列中的索引,而不是它的值。

+ +

If you need to find the position of an element or whether an element exists in an array, use {{jsxref("Array.prototype.indexOf()")}} or {{jsxref("Array.prototype.includes()")}}.

+ +

語法

+ +
arr.find(callback[, thisArg])
+ +

參數

+ +
+
callback
+
會處理陣列中每個元素的函數,它使用三個參數: +
+
element
+
在陣列中正被處理的元素。
+
index{{optional_inline}}
+
在陣列中正被處理的元素的索引。
+
array{{optional_inline}}
+
呼叫 find 的陣列。
+
+
+
thisArg {{Optional_inline}}
+
執行 callback 函式時被當作 this 的物件。
+
+ +

回傳值

+ +

若元素通過測試則為其值;否則為 {{jsxref("undefined")}}。

+ +

描述

+ +

find 方法會對每個元素執行一次 callback 函式,直到找到一個讓 callback 函式回傳 true 的元素。當元素被找到的時候,find 會立刻回傳該元素,否則 find 會回傳 {{jsxref("undefined")}}。callback 會被使用於陣列索引自 0length - 1,並會被用於每一個的陣列索引,而不僅是那些有賦值的索引。這代表此方法在稀疏陣列(sparse arrays)上的效能可能較其他只存取已賦值索引的方法來的差。

+ +

callback 函式被呼叫時會傳入三個參數:元素的值、元素索引,以及正被迭代的陣列物件。

+ +

如果提供 thisArg 參數予 find,其將會被當作 callback 每次被呼叫的 this。若是沒提供,則會使用 {{jsxref("undefined")}}。

+ +

find 並不會改變呼叫該方法的陣列。

+ +

The range of elements processed by find is set before the first invocation of callback. Elements that are appended to the array after the call to find begins will not be visited by callback. If an existing, unvisited element of the array is changed by callback, its value passed to the visiting callback will be the value at the time that find visits that element's index; elements that are deleted are still visited.

+ +

範例

+ +

Find an object in an array by one of its properties

+ +
var inventory = [
+    {name: 'apples', quantity: 2},
+    {name: 'bananas', quantity: 0},
+    {name: 'cherries', quantity: 5}
+];
+
+function isCherries(fruit) {
+    return fruit.name === 'cherries';
+}
+
+console.log(inventory.find(isCherries));
+// { name: 'cherries', quantity: 5 }
+ +

在陣列中找質數

+ +

以下範例在陣列中找出一個屬於質數的元素,如果裡面不含質數則回傳 {{jsxref("undefined")}}。

+ +
function isPrime(element, index, array) {
+  var start = 2;
+  while (start <= Math.sqrt(element)) {
+    if (element % start++ < 1) {
+      return false;
+    }
+  }
+  return element > 1;
+}
+
+console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found
+console.log([4, 5, 8, 12].find(isPrime)); // 5
+
+ +

The following examples show that non-existent and deleted elements are visited and that the value passed to the callback is their value when visited.

+ +
// Declare array with no element at index 2, 3 and 4
+var a = [0,1,,,,5,6];
+
+// Shows all indexes, not just those that have been assigned values
+a.find(function(value, index) {
+  console.log('Visited index ' + index + ' with value ' + value);
+});
+
+// Shows all indexes, including deleted
+a.find(function(value, index) {
+
+  // Delete element 5 on first iteration
+  if (index == 0) {
+    console.log('Deleting a[5] with value ' + a[5]);
+    delete a[5];
+  }
+  // Element 5 is still visited even though deleted
+  console.log('Visited index ' + index + ' with value ' + value);
+});
+
+
+ +

Polyfill

+ +

這個方法在 ECMAScript 2015 中首次被規範,可能尚未在所有 JavaScript 應用中被實作。你可以使用以下程式片段來 polyfill Array.prototype.find

+ +
// https://tc39.github.io/ecma262/#sec-array.prototype.find
+if (!Array.prototype.find) {
+  Object.defineProperty(Array.prototype, 'find', {
+    value: function(predicate) {
+     // 1. Let O be ? ToObject(this value).
+      if (this == null) {
+        throw new TypeError('"this" is null or not defined');
+      }
+
+      var o = Object(this);
+
+      // 2. Let len be ? ToLength(? Get(O, "length")).
+      var len = o.length >>> 0;
+
+      // 3. If IsCallable(predicate) is false, throw a TypeError exception.
+      if (typeof predicate !== 'function') {
+        throw new TypeError('predicate must be a function');
+      }
+
+      // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
+      var thisArg = arguments[1];
+
+      // 5. Let k be 0.
+      var k = 0;
+
+      // 6. Repeat, while k < len
+      while (k < len) {
+        // a. Let Pk be ! ToString(k).
+        // b. Let kValue be ? Get(O, Pk).
+        // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
+        // d. If testResult is true, return kValue.
+        var kValue = o[k];
+        if (predicate.call(thisArg, kValue, k, o)) {
+          return kValue;
+        }
+        // e. Increase k by 1.
+        k++;
+      }
+
+      // 7. Return undefined.
+      return undefined;
+    }
+  });
+}
+
+ +

If you need to support truly obsolete JavaScript engines that don't support Object.defineProperty, it's best not to polyfill Array.prototype methods at all, as you can't make them non-enumerable.

+ +

規範

+ + + + + + + + + + + + + + + + + + + +
規範狀態備註
{{SpecName('ES6', '#sec-array.prototype.find', 'Array.prototype.find')}}{{Spec2('ES6')}}首次定義
{{SpecName('ESDraft', '#sec-array.prototype.find', 'Array.prototype.find')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.find")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/findindex/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/findindex/index.html new file mode 100644 index 0000000000..4271ae9ef1 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/findindex/index.html @@ -0,0 +1,181 @@ +--- +title: Array.prototype.findIndex() +slug: Web/JavaScript/Reference/Global_Objects/Array/findIndex +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/findIndex +--- +
{{JSRef}}
+ +

findIndex() 方法將依據提供的測試函式,尋找陣列中符合的元素,並返回其 index(索引)。如果沒有符合的對象,將返回 -1 。

+ +
{{EmbedInteractiveExample("pages/js/array-findindex.html")}}
+ + + +
 
+ +

另請參見 {{jsxref("Array.find", "find()")}} 方法,它返回陣列中找到的元素的,而不是其索引。

+ +

語法

+ +
arr.findIndex(callback[, thisArg])
+ +

參數

+ +
+
callback
+
針對陣列中的每個元素,都會執行該回呼函式,執行時會自動傳入下面三個參數: +
+
element
+
當前元素。
+
index{{optional_inline}}
+
當前元素的索引。
+
array{{optional_inline}}
+
呼叫 findIndex 的陣列。
+
+
+
thisArg{{optional_inline}}
+
可選的。執行 callback 時作為 this 對象的值。
+
+ +

回傳值

+ +

An index in the array if an element passes the test; otherwise, -1.

+ +

描述

+ +

findIndex 方法對陣列中的每一個索引:0..length-1(含)的元素執行一次 callback 直到有一個 callback 返回 truthy 值(一個可強制轉型(coerces)為 true 的值)。如果找到了一個這樣的元素,則 findIndex 將會立刻返回此次迭代的索引。若回呼函式從未回傳一個 truthy 值,或陣列的 length 為 0,則 findIndex 將會返回 -1。不像其他的陣列方法如 some 那樣,於稀疏(sparse)陣列上 callback 仍會被呼叫,即使該索引的項目在陣列中並不存在。

+ +

callback 被呼叫時會傳入三個參數:元素的值、元素的索引,以及被迭代的陣列物件。

+ +

如果一個 thisArg 參數被提供給 findIndex,它將會被當作 this 使用在每次回呼函式被調用的時候。如果沒有被提供,將會使用 {{jsxref("undefined")}}。

+ +

findIndex 不會修改呼叫此方法的陣列。

+ +

在第一次呼叫 callback 函式時會確定元素的索引範圍,因此在 findIndex 方法開始執行之後添加到陣列的新元素將不會被 callback 函式訪問到。如果陣列中一個尚未被 callback 函式訪問到的元素的值被 callback 函式所改變,那麼當 callback 函式訪問到它時,它的值是將是根據它在陣列中的索引所訪問到的當前值;被刪除的元素仍然會被訪問到。

+ +

範例

+ +

尋找陣列中首個質數元素的索引

+ +

以下的範例演示了如何查找一個陣列中首個質數元素的索引,找不到則返回 -1。

+ +
function isPrime(element, index, array) {
+  var start = 2;
+  while (start <= Math.sqrt(element)) {
+    if (element % start++ < 1) {
+      return false;
+    }
+  }
+  return element > 1;
+}
+
+console.log([4, 6, 8, 12].findIndex(isPrime)); // -1, not found
+console.log([4, 6, 7, 12].findIndex(isPrime)); // 2
+
+ +

使用箭頭函式尋找索引

+ +

以下範例為使用箭頭函式尋找水果的索引。

+ +
const fruits = ["apple", "banana", "cantaloupe", "blueberries", "grapefruit"];
+
+const index = fruits.findIndex(fruit => fruit === "blueberries");
+
+console.log(index); // 3
+console.log(fruits[index]); // blueberries
+
+ +

Polyfill

+ +
// https://tc39.github.io/ecma262/#sec-array.prototype.findIndex
+if (!Array.prototype.findIndex) {
+  Object.defineProperty(Array.prototype, 'findIndex', {
+    value: function(predicate) {
+     // 1. Let O be ? ToObject(this value).
+      if (this == null) {
+        throw new TypeError('"this" is null or not defined');
+      }
+
+      var o = Object(this);
+
+      // 2. Let len be ? ToLength(? Get(O, "length")).
+      var len = o.length >>> 0;
+
+      // 3. If IsCallable(predicate) is false, throw a TypeError exception.
+      if (typeof predicate !== 'function') {
+        throw new TypeError('predicate must be a function');
+      }
+
+      // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
+      var thisArg = arguments[1];
+
+      // 5. Let k be 0.
+      var k = 0;
+
+      // 6. Repeat, while k < len
+      while (k < len) {
+        // a. Let Pk be ! ToString(k).
+        // b. Let kValue be ? Get(O, Pk).
+        // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
+        // d. If testResult is true, return k.
+        var kValue = o[k];
+        if (predicate.call(thisArg, kValue, k, o)) {
+          return k;
+        }
+        // e. Increase k by 1.
+        k++;
+      }
+
+      // 7. Return -1.
+      return -1;
+    }
+  });
+}
+
+ +

如果您需要相容過時的不支援 Object.defineProperty 的 JavaScript 引擎,最好不要使用 polyfill 來填充 Array.prototype 方法,因為無法使它們成為不可枚舉的(non-enumerable)屬性。

+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-array.prototype.findindex', 'Array.prototype.findIndex')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.findIndex', 'Array.prototype.findIndex')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.findIndex")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/flat/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/flat/index.html new file mode 100644 index 0000000000..8a6a4b2549 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/flat/index.html @@ -0,0 +1,148 @@ +--- +title: Array.prototype.flat() +slug: Web/JavaScript/Reference/Global_Objects/Array/flat +tags: + - JavaScript + - 實驗中 + - 方法 + - 陣列 +translation_of: Web/JavaScript/Reference/Global_Objects/Array/flat +--- +
{{JSRef}} {{SeeCompatTable}}
+ +

flat() 函數以遞迴方式將特定深度的子陣列重新串接成為一新的陣列

+ + + + + +

語法

+ +
var newArray = arr.flat([depth]);
+ +

參數

+ +
+
depth {{optional_inline}}
+
指定巢狀陣列展開的深度。預設為1。
+
+ +

回傳值

+ +

函數將會回傳一個由原先陣列的子陣列串接而成的新陣列。

+ + + +

範例

+ +

展開巢狀陣列

+ +
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()函數會自動清除陣列中空的元素

+ +
var arr4 = [1, 2, , 4, 5];
+arr4.flat();
+// [1, 2, 4, 5]
+
+ +

替代方案

+ +

reduce 與 concat

+ +
var arr1 = [1, 2, [3, 4]];
+arr1.flat();
+
+//展開單層陣列
+arr1.reduce((acc, val) => acc.concat(val), []);// [1, 2, 3, 4]
+
+ + + +
//欲展開更深層的巢狀結構請使用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]
+
+ + + +
//使用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]
+
+ +
// 递归版本的反嵌套
+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;
+}
+ +

規範

+ + + + + + + + + + + + + + +
SpecificationStatusComment
Array.prototype.flat proposalCandidate (3)
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.flat")}}

+
+ +

See also

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/foreach/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/foreach/index.html new file mode 100644 index 0000000000..df1dc91684 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/foreach/index.html @@ -0,0 +1,297 @@ +--- +title: Array.prototype.forEach() +slug: Web/JavaScript/Reference/Global_Objects/Array/forEach +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/forEach +--- +
{{JSRef}}
+ +

forEach() 方法會將陣列內的每個元素,皆傳入並執行給定的函式一次。

+ +
{{EmbedInteractiveExample("pages/js/array-foreach.html")}}
+ + + +

語法

+ +
arr.forEach(function callback(currentValue[, index[, array]]) {
+    //your iterator
+}[, thisArg]);
+ +

參數

+ +
+
callback
+
這個 callback 函式將會把 Array 中的每一個元素作為參數,帶進本 callback 函式裡,每個元素各執行一次,接收三個參數: +
+
currentValue
+
代表目前被處理中的 Array 之中的那個元素。
+
index{{optional_inline}}
+
代表目前被處理中的 Array 之中的那個元素的index.
+
array{{optional_inline}}
+
呼叫 forEach() 方法的那個 Array 本身,也就是上面語法中的 arr。
+
+
+
thisArg {{Optional_inline}}
+
執行 callback 回呼函式的 this(即參考之 Object)值。
+
+ +

回傳值

+ +

{{jsxref("undefined")}}。

+ +

描述

+ +

forEach() executes the provided callback once for each element present in the array in ascending order. It is not invoked for index properties that have been deleted or are uninitialized (i.e. on sparse arrays).

+ +

callback is invoked with three arguments:

+ + + +

If a thisArg parameter is provided to forEach(), it will be used as callback's this value.  Otherwise, the value {{jsxref("undefined")}} will be used as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.

+ +

The range of elements processed by forEach() is set before the first invocation of callback. Elements that are appended to the array after the call to forEach() begins will not be visited by callback. If the values of existing elements of the array are changed, the value passed to callback will be the value at the time forEach() visits them; elements that are deleted before being visited are not visited. If elements that are already visited are removed (e.g. using {{jsxref("Array.prototype.shift()", "shift()")}}) during the iteration, later elements will be skipped - see example below.

+ +

forEach() executes the callback function once for each array element; unlike {{jsxref("Array.prototype.map()", "map()")}} or {{jsxref("Array.prototype.reduce()", "reduce()")}} it always returns the value {{jsxref("undefined")}} and is not chainable. The typical use case is to execute side effects at the end of a chain.

+ +

forEach() does not mutate the array on which it is called (although callback, if invoked, may do so).

+ +
+

除非是拋出異常,否則並沒有中止 forEach() 迴圈的辦法。如果你需要這樣做,forEach() 就是錯誤的用法,相反的,應該要用簡單的迴圈。如果你要測試陣列裡面的元素並回傳布林值,可以用 {{jsxref("Array.prototype.every()", "every()")}} 或 {{jsxref("Array.prototype.some()", "some()")}}。如果可以的話,新的方法 {{jsxref("Array.prototype.find()", "find()")}} 或 {{jsxref("Array.prototype.findIndex()", "findIndex()")}} 也可以用於 true 值之後提前終止。

+
+ +

範例

+ +

Converting from for to forEach

+ +

before

+ +
const items = ['item1', 'item2', 'item3'];
+const copy = [];
+
+for (let i=0; i<items.length; i++) {
+  copy.push(items[i])
+}
+
+ +

after

+ +
const items = ['item1', 'item2', 'item3'];
+const copy = [];
+
+items.forEach(function(item){
+  copy.push(item)
+});
+
+
+ +

 

+ +

Printing the contents of an array

+ +

The following code logs a line for each element in an array:

+ +
function logArrayElements(element, index, array) {
+  console.log('a[' + index + '] = ' + element);
+}
+
+// Notice that index 2 is skipped since there is no item at
+// that position in the array.
+[2, 5, , 9].forEach(logArrayElements);
+// logs:
+// a[0] = 2
+// a[1] = 5
+// a[3] = 9
+
+ +

Using thisArg

+ +

The following (contrived) example updates an object's properties from each entry in the array:

+ +
function Counter() {
+  this.sum = 0;
+  this.count = 0;
+}
+Counter.prototype.add = function(array) {
+  array.forEach(function(entry) {
+    this.sum += entry;
+    ++this.count;
+  }, this);
+  // ^---- Note
+};
+
+const obj = new Counter();
+obj.add([2, 5, 9]);
+obj.count;
+// 3
+obj.sum;
+// 16
+
+ +

Since the thisArg parameter (this) is provided to forEach(), it is passed to callback each time it's invoked, for use as its this value.

+ +
+

If passing the function argument using an arrow function expression the thisArg parameter can be omitted as arrow functions lexically bind the {{jsxref("Operators/this", "this")}} value.

+
+ +

An object copy function

+ +

The following code creates a copy of a given object. There are different ways to create a copy of an object; the following is just one way and is presented to explain how Array.prototype.forEach() works by using ECMAScript 5 Object.* meta property functions.

+ +
function copy(obj) {
+  const copy = Object.create(Object.getPrototypeOf(obj));
+  const propNames = Object.getOwnPropertyNames(obj);
+
+  propNames.forEach(function(name) {
+    const desc = Object.getOwnPropertyDescriptor(obj, name);
+    Object.defineProperty(copy, name, desc);
+  });
+
+  return copy;
+}
+
+const obj1 = { a: 1, b: 2 };
+const obj2 = copy(obj1); // obj2 looks like obj1 now
+
+ +

If the array is modified during iteration, other elements might be skipped.

+ +

The following example logs "one", "two", "four". When the entry containing the value "two" is reached, the first entry of the whole array is shifted off, which results in all remaining entries moving up one position. Because element "four" is now at an earlier position in the array, "three" will be skipped. forEach() does not make a copy of the array before iterating.

+ +
var words = ['one', 'two', 'three', 'four'];
+words.forEach(function(word) {
+  console.log(word);
+  if (word === 'two') {
+    words.shift();
+  }
+});
+// one
+// two
+// four
+
+ +

Polyfill

+ +

forEach() 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 forEach() in implementations that don't natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming {{jsxref("Object")}} and {{jsxref("TypeError")}} have their original values and that callback.call() evaluates to the original value of {{jsxref("Function.prototype.call()")}}.

+ +
// Production steps of ECMA-262, Edition 5, 15.4.4.18
+// Reference: http://es5.github.io/#x15.4.4.18
+if (!Array.prototype.forEach) {
+
+  Array.prototype.forEach = function(callback/*, thisArg*/) {
+
+    var T, k;
+
+    if (this == null) {
+      throw new TypeError('this is null or not defined');
+    }
+
+    // 1. Let O be the result of calling toObject() passing the
+    // |this| value as the argument.
+    var O = Object(this);
+
+    // 2. Let lenValue be the result of calling the Get() internal
+    // method of O with the argument "length".
+    // 3. Let len be toUint32(lenValue).
+    var len = O.length >>> 0;
+
+    // 4. If isCallable(callback) is false, throw a TypeError exception.
+    // See: http://es5.github.com/#x9.11
+    if (typeof callback !== 'function') {
+      throw new TypeError(callback + ' is not a function');
+    }
+
+    // 5. If thisArg was supplied, let T be thisArg; else let
+    // T be undefined.
+    if (arguments.length > 1) {
+      T = arguments[1];
+    }
+
+    // 6. Let k be 0.
+    k = 0;
+
+    // 7. Repeat while k < len.
+    while (k < len) {
+
+      var kValue;
+
+      // a. Let Pk be ToString(k).
+      //    This is implicit for LHS operands of the in operator.
+      // b. Let kPresent be the result of calling the HasProperty
+      //    internal method of O with argument Pk.
+      //    This step can be combined with c.
+      // c. If kPresent is true, then
+      if (k in O) {
+
+        // i. Let kValue be the result of calling the Get internal
+        // method of O with argument Pk.
+        kValue = O[k];
+
+        // ii. Call the Call internal method of callback with T as
+        // the this value and argument list containing kValue, k, and O.
+        callback.call(T, kValue, k, O);
+      }
+      // d. Increase k by 1.
+      k++;
+    }
+    // 8. return undefined.
+  };
+}
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.18', 'Array.prototype.forEach')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.foreach', 'Array.prototype.forEach')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.forEach")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/from/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/from/index.html new file mode 100644 index 0000000000..229b92f5e6 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/from/index.html @@ -0,0 +1,215 @@ +--- +title: Array.from() +slug: Web/JavaScript/Reference/Global_Objects/Array/from +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Method + - Reference + - polyfill + - 陣列 +translation_of: Web/JavaScript/Reference/Global_Objects/Array/from +--- +
{{JSRef}}
+ +

Array.from() 方法會從類陣列(array-like)或是可迭代(iterable)物件建立一個新的 Array 實體。

+ +
{{EmbedInteractiveExample("pages/js/array-from.html")}}
+ + + +

參數

+ +
+
arrayLike
+
將類陣列或可迭代物件轉換成陣列
+
mapFn {{Optional_inline}}
+
Map 函式走訪陣列中的每一個元素。
+
thisArg {{Optional_inline}}
+
mapFn 函式執行時的 this 對象。
+
+ +

回傳值

+ +

一個新的 {{jsxref("Array")}} 實體。

+ +

描述

+ +

Array.from() 讓你從這些物件建立陣列:

+ + + +

Array.from() 有個可選用的參數 mapFn,它允許你在建立出新的陣列實體之後,可以接著對陣列(或是其子類別物件)中的每一個元素執行 {{jsxref("Array.prototype.map", "map")}} 函式。更清楚地說, Array.from(obj, mapFn, thisArg)Array.from(obj).map(mapFn, thisArg) 的結果是一樣的,除非所建立的不是一個可用的中介陣列(intermediate array)。這對於某些陣列的子類別來說就很重要,例如型別陣列,因為中介陣列必須要把內容值做一番截頭去尾的操作來讓它們變成適合的物件型態。

+ +

from() 方法的 length 屬性值為 1。

+ +

在 ES2015,類別語法允許原生內建的物件以及使用者自定義的物件可以被子類別化(sub-classing);因此,靜態方法像是 Array.from,是「繼承」了 Array 的子類別後,然後建立新的子類別的實體,而不是建立 Array 本身。

+ +

範例

+ +

從字串產生陣列

+ +
Array.from('foo');
+// ["f", "o", "o"]
+ +

從集合產生陣列

+ +
var s = new Set(['foo', window]);
+Array.from(s);
+// ["foo", window]
+ +

從映射產生陣列

+ +
var m = new Map([[1, 2], [2, 4], [4, 8]]);
+Array.from(m);
+// [[1, 2], [2, 4], [4, 8]]
+ +

從類陣列物件(arguments)產生陣列

+ +
function f() {
+  return Array.from(arguments);
+}
+
+f(1, 2, 3);
+
+// [1, 2, 3]
+ +

使用箭頭函式及 Array.from

+ +
// 使用箭頭函式作為 map 函式來
+// 操作元素
+Array.from([1, 2, 3], x => x + x);
+// [2, 4, 6]
+
+// 產生數值序列
+// 因為陣列中的每個位置都會被初始化為 `undefined`,
+// 下方 `v` 會是 `undefined`
+Array.from({length: 5}, (v, i) => i);
+// [0, 1, 2, 3, 4]
+
+ +

Polyfill

+ +

Array.from 在 ECMA-262 標準第六版(ES2015)被加入;在某些實作可能尚未被支援。你可以將下面的程式碼插入到妳的 script 的最前面,如果你使用的工作環境不具有原生支援 Array.from 的能力。這個演算法根據 ECMA-262 第六版中的規範實現,假定 ObjectTypeError 它們本身已具有值且 callback.call 對應到原本 {{jsxref("Function.prototype.call")}} 的值。除此之外,因為 Polyfill 無法實現真正的迭代,這個實作不支援 ECMA-262 第六版中所定義的泛型迭代。

+ +
// Production steps of ECMA-262, Edition 6, 22.1.2.1
+if (!Array.from) {
+  Array.from = (function () {
+    var toStr = Object.prototype.toString;
+    var isCallable = function (fn) {
+      return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
+    };
+    var toInteger = function (value) {
+      var number = Number(value);
+      if (isNaN(number)) { return 0; }
+      if (number === 0 || !isFinite(number)) { return number; }
+      return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
+    };
+    var maxSafeInteger = Math.pow(2, 53) - 1;
+    var toLength = function (value) {
+      var len = toInteger(value);
+      return Math.min(Math.max(len, 0), maxSafeInteger);
+    };
+
+    // The length property of the from method is 1.
+    return function from(arrayLike/*, mapFn, thisArg */) {
+      // 1. Let C be the this value.
+      var C = this;
+
+      // 2. Let items be ToObject(arrayLike).
+      var items = Object(arrayLike);
+
+      // 3. ReturnIfAbrupt(items).
+      if (arrayLike == null) {
+        throw new TypeError('Array.from requires an array-like object - not null or undefined');
+      }
+
+      // 4. If mapfn is undefined, then let mapping be false.
+      var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
+      var T;
+      if (typeof mapFn !== 'undefined') {
+        // 5. else
+        // 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
+        if (!isCallable(mapFn)) {
+          throw new TypeError('Array.from: when provided, the second argument must be a function');
+        }
+
+        // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
+        if (arguments.length > 2) {
+          T = arguments[2];
+        }
+      }
+
+      // 10. Let lenValue be Get(items, "length").
+      // 11. Let len be ToLength(lenValue).
+      var len = toLength(items.length);
+
+      // 13. If IsConstructor(C) is true, then
+      // 13. a. Let A be the result of calling the [[Construct]] internal method
+      // of C with an argument list containing the single item len.
+      // 14. a. Else, Let A be ArrayCreate(len).
+      var A = isCallable(C) ? Object(new C(len)) : new Array(len);
+
+      // 16. Let k be 0.
+      var k = 0;
+      // 17. Repeat, while k < len… (also steps a - h)
+      var kValue;
+      while (k < len) {
+        kValue = items[k];
+        if (mapFn) {
+          A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
+        } else {
+          A[k] = kValue;
+        }
+        k += 1;
+      }
+      // 18. Let putStatus be Put(A, "length", len, true).
+      A.length = len;
+      // 20. Return A.
+      return A;
+    };
+  }());
+}
+
+ +

規格

+ + + + + + + + + + + + + + + + + + + +
規格狀態備註
{{SpecName('ES2015', '#sec-array.from', 'Array.from')}}{{Spec2('ES2015')}}首次定義。
{{SpecName('ESDraft', '#sec-array.from', 'Array.from')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.from")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/includes/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/includes/index.html new file mode 100644 index 0000000000..6d3d0e0cb2 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/includes/index.html @@ -0,0 +1,175 @@ +--- +title: Array.prototype.includes() +slug: Web/JavaScript/Reference/Global_Objects/Array/includes +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/includes +--- +
{{JSRef}}
+ +

includes() 方法會判斷陣列是否包含特定的元素,並以此來回傳 truefalse

+ +
{{EmbedInteractiveExample("pages/js/array-includes.html")}}
+ + + +

語法

+ +
arr.includes(searchElement[, fromIndex])
+
+ +

參數

+ +
+
searchElement
+
要搜尋的元素。
+
fromIndex {{optional_inline}}
+
要於此陣列中開始搜尋 searchElement 的位置。如為負數值,則自 array.length + fromIndex 開始向後搜尋。預設值為 0。
+
+ +

回傳值

+ +

布林值({{jsxref("Boolean")}})。

+ +

範例

+ +
[1, 2, 3].includes(2);     // true
+[1, 2, 3].includes(4);     // false
+[1, 2, 3].includes(3, 3);  // false
+[1, 2, 3].includes(3, -1); // true
+[1, 2, NaN].includes(NaN); // true
+
+ +

fromIndex 大於或等於陣列長度

+ +

如果 fromIndex大於或等於陣列長度, 會回傳false. 此陣列將不會被搜尋.

+ +
var arr = ['a', 'b', 'c'];
+
+arr.includes('c', 3);   // false
+arr.includes('c', 100); // false
+ +

Computed index is less than 0

+ +

If fromIndex is negative, the computed index is calculated to be used as a position in the array at which to begin searching for searchElement. If the computed index is less than 0, the entire array will be searched.

+ +
// array length is 3
+// fromIndex is -100
+// computed index is 3 + (-100) = -97
+
+var arr = ['a', 'b', 'c'];
+
+arr.includes('a', -100); // true
+arr.includes('b', -100); // true
+arr.includes('c', -100); // true
+ +

includes() used as a generic method

+ +

includes() method is intentionally generic. It does not require this value to be an Array object, so it can be applied to other kinds of objects (e.g. array-like objects). The example below illustrates includes() method called on the function's arguments object.

+ +
(function() {
+  console.log([].includes.call(arguments, 'a')); // true
+  console.log([].includes.call(arguments, 'd')); // false
+})('a','b','c');
+ +

Polyfill

+ +
// https://tc39.github.io/ecma262/#sec-array.prototype.includes
+if (!Array.prototype.includes) {
+  Object.defineProperty(Array.prototype, 'includes', {
+    value: function(searchElement, fromIndex) {
+
+      if (this == null) {
+        throw new TypeError('"this" is null or not defined');
+      }
+
+      // 1. Let O be ? ToObject(this value).
+      var o = Object(this);
+
+      // 2. Let len be ? ToLength(? Get(O, "length")).
+      var len = o.length >>> 0;
+
+      // 3. If len is 0, return false.
+      if (len === 0) {
+        return false;
+      }
+
+      // 4. Let n be ? ToInteger(fromIndex).
+      //    (If fromIndex is undefined, this step produces the value 0.)
+      var n = fromIndex | 0;
+
+      // 5. If n ≥ 0, then
+      //  a. Let k be n.
+      // 6. Else n < 0,
+      //  a. Let k be len + n.
+      //  b. If k < 0, let k be 0.
+      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
+
+      function sameValueZero(x, y) {
+        return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
+      }
+
+      // 7. Repeat, while k < len
+      while (k < len) {
+        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
+        // b. If SameValueZero(searchElement, elementK) is true, return true.
+        if (sameValueZero(o[k], searchElement)) {
+          return true;
+        }
+        // c. Increase k by 1.
+        k++;
+      }
+
+      // 8. Return false
+      return false;
+    }
+  });
+}
+
+ +

If you need to support truly obsolete JavaScript engines that don't support Object.defineProperty, it's best not to polyfill Array.prototype methods at all, as you can't make them non-enumerable.

+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES7', '#sec-array.prototype.includes', 'Array.prototype.includes')}}{{Spec2('ES7')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.includes', 'Array.prototype.includes')}}{{Spec2('ESDraft')}}
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.includes")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/index.html new file mode 100644 index 0000000000..fe344c1811 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/index.html @@ -0,0 +1,457 @@ +--- +title: Array +slug: Web/JavaScript/Reference/Global_Objects/Array +tags: + - Array + - JavaScript + - NeedsTranslation + - TopicStub + - 陣列 +translation_of: Web/JavaScript/Reference/Global_Objects/Array +--- +
{{JSRef}}
+ +

JavaScript 中的 Array 全域物件被用於建構陣列;陣列為高階(high-level)、似列表(list-like)的物件。陣列在Javascript 裡面並沒有固定的長度與型別。由於陣列的長度可以隨時被改變,所以並不能保證陣列的密度。這取決於開發者如何使用陣列。一般來說,這是個非常方便的特性,但如果這並不適用於你的開發工作,你也許會考慮使用型別陣列。

+ +

建立陣列

+ +
var fruits = ['Apple', 'Banana'];
+
+console.log(fruits.length);
+// 2
+
+ +

(透過索引)取得陣列項目

+ +
var first = fruits[0];
+// Apple
+
+var last = fruits[fruits.length - 1];
+// Banana
+
+ +

迭代陣列

+ +
fruits.forEach(function(item, index, array) {
+  console.log(item, index);
+});
+// Apple 0
+// Banana 1
+
+ +

加入項目至陣列末端

+ +
var newLength = fruits.push('Orange');
+// ["Apple", "Banana", "Orange"]
+
+ +

移除陣列末端項目

+ +
var last = fruits.pop(); // 移除 (最末端的) Orange
+// ["Apple", "Banana"];
+
+ +

移除陣列前端項目

+ +
var first = fruits.shift(); // 移除 (最前端的) Apple
+// ["Banana"];
+ +

加入項目至陣列前端

+ +
var newLength = fruits.unshift('Strawberry') // 加到陣列前端
+// ["Strawberry", "Banana"];
+
+ +

在陣列中尋找項目的索引

+ +
fruits.push('Mango');
+// ["Strawberry", "Banana", "Mango"]
+
+var pos = fruits.indexOf('Banana');
+// 1
+
+ +

移除指定索引位置的項目

+ +
var removedItem = fruits.splice(pos, 1); // 移除 pos 起的 1 個項目
+
+// ["Strawberry", "Mango"]
+ +

移除指定索引位置起的多個項目

+ +
var vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot'];
+console.log(vegetables);
+// ["Cabbage", "Turnip", "Radish", "Carrot"]
+
+var pos = 1, n = 2;
+
+var removedItems = vegetables.splice(pos, n);
+// 這就是移除項目的方式,
+// n 表示從該位置 (pos) 開始,一直到陣列的尾端有多少項目需要移除
+
+console.log(vegetables);
+// ["Cabbage", "Carrot"] (原始的陣列被改變)
+
+console.log(removedItems);
+// ["Turnip", "Radish"]
+ +

複製陣列

+ +
var shallowCopy = fruits.slice(); // 這就是複製陣列的方式
+// ["Strawberry", "Mango"]
+
+ +

語法

+ +
[element0, element1, ..., elementN]
+new Array(element0, element1[, ...[, elementN]])
+new Array(arrayLength)
+ +

參數

+ +
+
elementN
+
除了只傳遞一個參數給 Array 構造函數,且該參數為一個數字的情況(詳見下方的 arrayLength 參數),JavaScript 陣列會以傳入的元素進行初始化。
+
請注意,這種特殊情況僅適用於以 Array 構造函數建立的 JavaScript 陣列,而不適用於以括號語法建立的陣列常值(Array Literals)。
+
arrayLength
+
如果傳遞給 Array 構造函數的唯一參數是 0 和 232-1(含)之間的整數,將回傳一個新的 JavaScript 陣列,其長度被設定為這個數字。如果參數是任何其他數值,將拋出 {{jsxref("RangeError")}} 異常。
+
+ +

說明

+ +

Array(「陣列」)是類似列表(list)的物件(Object),它們的原型(Prototype)擁有方法(methods)來執行遍歷和變異操作。JavaScript 陣列的長度(元素數量),以及其元素的類型都不是固定的。取決於工程師如何選擇使用陣列,可以隨時更改陣列的長度,也可不連續儲存資料, 所以並不保證這些資料是集中的。一般情況下,這些特性很方便使用;但若這些功能都不符合您的用途,您可能會想使用型別陣列(typed arrays)。

+ +

有些人認為即便會發生警告,仍然不應該使用關聯陣列,而應該使用 {{jsxref("Global_Objects/Object", "objects")}}。您可參考輕量級 JavaScript 字典當中的範例。

+ +

存取陣列元素

+ +

JavaScript 陣列是 zero-indexed:陣列元素的索引值編排從 0 開始,而最後一個元素的索引值等同於陣列的 {{jsxref("Array.length", "length")}} 屬性減 1。

+ +
var arr = ['this is the first element', 'this is the second element'];
+console.log(arr[0]);              // 紀錄出 'this is the first element'
+console.log(arr[1]);              // 記錄出 'this is the second element'
+console.log(arr[arr.length - 1]); // 記錄出 'this is the second element'
+
+ +

Array 元素同時也是物件的屬性,與 toString 是一種屬性相同。但若要透過下面這種方式存取陣列元素,因為屬性名稱無效的關係,會發生語法錯誤:

+ +
console.log(arr.0); // 語法錯誤
+
+ +

會造成如此的原因沒有什麼特別的,在 JavaScript 當中無法用小數點的方式來參照一個名稱開頭為數字的屬性,而必須括號的表示方式來存取。舉例來說,若您有個物件的屬性名稱為「3d」,就只能用括號的方式來參照。

+ +

請看下列範例:

+ +
var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010];
+console.log(years.0);   // 語法錯誤
+console.log(years[0]);  // 程式正常
+
+ +
renderer.3d.setTexture(model, 'character.png');     // 語法錯誤
+renderer['3d'].setTexture(model, 'character.png');  // 程式正常
+
+ +

注意:以這個 '3d' 例子來說,必須用引號將 3d 包起來。您也可以將 JavaScript 陣列的索引用引號包起來(例如使用 years['2'] 而不用 years[2]),但這不是必要的。JavaScript 會透過隱含的 toString,將 years[2] 當中的 2 強制轉換為字串。由於這個原因,'2''02' 會參照到 years 物件中的不同項目,下列程式範例結果可能回傳 true

+ +
console.log(years['2'] != years['02']);
+
+ +

另一種類似的情況是,物件屬性剛好與保留字(!)相同的情況。這種情況下僅能透過括號表示方式當中的字串常值來存取:

+ +
var promise = {
+  'var'  : 'text',
+  'array': [1, 2, 3, 4]
+};
+
+console.log(promise['var']);
+
+ +

length 與數值屬性的關係

+ +

JavaScript 陣列的 {{jsxref("Array.length", "length")}} 屬性和其數值屬性相關。許多陣列的方法被呼叫時會參考 {{jsxref("Array.length", "length")}} 屬性的值(例如 {{jsxref("Array.join", "join")}}、{{jsxref("Array.slice", "slice")}}、{{jsxref("Array.indexOf", "indexOf")}} 等)。而有另一些方法則會去改變 {{jsxref("Array.length", "length")}} 屬性的值,如 {{jsxref("Array.push", "push")}}、{{jsxref("Array.splice", "splice")}}。

+ +
var fruits = [];
+fruits.push('banana', 'apple', 'peach');
+
+console.log(fruits.length); // 3
+
+ +

如果給陣列設定一個數值屬性,其值為有效但超過當下範圍的陣列 index,JavaScript 引擎會依照此數值更新陣列的 {{jsxref("Array.length", "length")}} 屬性:

+ +
fruits[5] = 'mango';
+console.log(fruits[5]); // 'mango'
+console.log(Object.keys(fruits));  // ['0', '1', '2', '5']
+console.log(fruits.length); // 6
+
+ +

提高 {{jsxref("Array.length", "length")}} 屬性。

+ +
fruits.length = 10;
+console.log(Object.keys(fruits)); // ['0', '1', '2', '5']
+console.log(fruits.length); // 10
+
+ +
+

降低 {{jsxref("Array.length", "length")}} 屬性則會刪除陣列元素。

+ +
fruits.length = 2;
+console.log(Object.keys(fruits)); // ['0', '1']
+console.log(fruits.length); // 2
+
+ +

在 {{jsxref("Array.length")}} 頁面裡有進一步解釋。

+
+ +

使用 match 回傳結果來建立陣列

+ +

在字串與正規表示式之間的比對結果會產生一個 javascript 陣列。此陣列內含關於比對資訊的屬性與元素。 這樣的陣列由{{jsxref("RegExp.exec")}}, {{jsxref("String.match")}}, 和 {{jsxref("String.replace")}} 所產生。參考以下範例和表格,會有助於說明這些屬性和元素:

+ +
// 比對一個字元 d,後面接著一或多個 b,再接著一個 d
+// Remember matched b's and the following d
+// 忽略大小寫
+
+var myRe = /d(b+)(d)/i;
+var myArray = myRe.exec('cdbBdbsbz');
+
+ +

這項比對結果的屬性與元素參考如下:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
屬性/元素說明範例
input唯讀屬性,代表 正規表示式用以比對的原始字串。cdbBdbsbz
index唯讀屬性,代表在字串中比對得到的索引,是以零為基礎(從0開始)。1
[0]一個唯獨元素以表示最後符合的字串dbBd
[1], ...[n]Read-only elements that specify the parenthesized substring matches, if included in the regular expression. The number of possible parenthesized substrings is unlimited.[1]: bB
+ [2]: d
+ +

屬性

+ +
+
Array.length
+
Array 建構子的長度為 1。
+
{{jsxref("Array.@@species", "get Array[@@species]")}}
+
用來建立衍生物件的建構函數。
+
{{jsxref("Array.prototype")}}
+
可加入屬性至所有陣列物件。
+
+ +

方法

+ +
+
{{jsxref("Array.from()")}}
+
用類似陣列或可列舉物件,來建立新的 Array 實例。
+
{{jsxref("Array.isArray()")}}
+
若變數是陣列就回傳 true,否則回傳 false。
+
{{jsxref("Array.of()")}}
+
用可變數量的引數來建立新的 Array 實例,不論引數的數量或型別。
+
+ +

Array 實例

+ +

所有的陣列實例都繼承自 {{jsxref("Array.prototype")}}。若修改這個陣列建構子 (Array constructor) 的原型物件 (prototype object),將會影響所有的陣列實體。

+ +

屬性

+ +
{{page('/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Properties')}}
+ +

方法

+ +

Mutator methods

+ +
{{page('zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Mutator_methods')}}
+ +

Accessor methods

+ +
{{page('zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Accessor_methods')}}
+ +

Iteration methods

+ +
{{page('zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype', 'Iteration_methods')}}
+ +

Array 泛型方法

+ +
+

泛型陣列並非標準且已被棄用,將會在不久之後被去除。 

+
+ +

有時你想將陣列方法用於字串或其他類陣列物件(像是函數 {{jsxref("Functions/arguments", "arguments", "", 1)}})。藉此操作,你將此字串視為由字元組成的陣列(反之為將其他非陣列視為物件)。如範例,若要確認字串中的每個字元是不是字母,你可能會這樣寫:

+ +
function isLetter(character) {
+  return character >= 'a' && character <= 'z';
+}
+
+if (Array.prototype.every.call(str, isLetter)) {
+  console.log("The string '" + str + "' contains only letters!");
+}
+
+ +

這種表示法相當浪費,JavaScript 1.6 導入了一個通用方法:

+ +
if (Array.every(str, isLetter)) {
+  console.log("The string '" + str + "' contains only letters!");
+}
+
+ +

{{jsxref("Global_Objects/String", "Generics", "#String_generic_methods", 1)}} 也同樣可用於 {{jsxref("String")}}.

+ +

並非 ECMAScript 的標準,且不被非 Gecko 引擎的瀏覽器支援。你應該將你的物件用  {{jsxref("Array.from()")}} 轉為陣列,以標準替代原有的方法;雖然此方法可能不被舊的瀏覽器所支援:

+ +
if (Array.from(str).every(isLetter)) {
+  console.log("The string '" + str + "' contains only letters!");
+}
+
+ +

範例

+ +

範例:建立陣列

+ +

以下範例會產生長度為 0 的 msgArray 陣列,然後指派字串值到 msgArray[0]msgArray[99],使陣列的長度變為 100。

+ +
var msgArray = [];
+msgArray[0] = 'Hello';
+msgArray[99] = 'world';
+
+if (msgArray.length === 100) {
+  console.log('The length is 100.');
+}
+
+ +

建立二維陣列

+ +

以下範例會用字串產生一張西洋棋盤的二維陣列。第一步是將士兵 'p' 從 (6,4) 移動至 (4,4),然後清空原本的位置 (6,4)。

+ +
var board = [
+  ['R','N','B','Q','K','B','N','R'],
+  ['P','P','P','P','P','P','P','P'],
+  [' ',' ',' ',' ',' ',' ',' ',' '],
+  [' ',' ',' ',' ',' ',' ',' ',' '],
+  [' ',' ',' ',' ',' ',' ',' ',' '],
+  [' ',' ',' ',' ',' ',' ',' ',' '],
+  ['p','p','p','p','p','p','p','p'],
+  ['r','n','b','q','k','b','n','r'] ];
+
+console.log(board.join('\n') + '\n\n');
+
+// 將士兵往前移兩步
+board[4][4] = board[6][4];
+board[6][4] = ' ';
+console.log(board.join('\n'));
+
+ +

以下是輸出結果:

+ +
R,N,B,Q,K,B,N,R
+P,P,P,P,P,P,P,P
+ , , , , , , ,
+ , , , , , , ,
+ , , , , , , ,
+ , , , , , , ,
+p,p,p,p,p,p,p,p
+r,n,b,q,k,b,n,r
+
+R,N,B,Q,K,B,N,R
+P,P,P,P,P,P,P,P
+ , , , , , , ,
+ , , , , , , ,
+ , , , ,p, , ,
+ , , , , , , ,
+p,p,p,p, ,p,p,p
+r,n,b,q,k,b,n,r
+
+ +

使用陣列來以表格顯示多個數值

+ +
values = [];
+for (var x = 0; x < 10; x++){
+ values.push([
+  2 ** x,
+  2 * x ** 2
+ ])
+};
+console.table(values)
+ +

結果會是

+ +
0	1	0
+1	2	2
+2	4	8
+3	8	18
+4	16	32
+5	32	50
+6	64	72
+7	128	98
+8	256	128
+9	512	162
+ +

(第一欄為索引)

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
技術規格狀態備註
{{SpecName('ES1')}}{{Spec2('ES1')}}初次定義。
{{SpecName('ES5.1', '#sec-15.4', 'Array')}}{{Spec2('ES5.1')}}加入新方法:{{jsxref("Array.isArray")}}, {{jsxref("Array.prototype.indexOf", "indexOf")}}, {{jsxref("Array.prototype.lastIndexOf", "lastIndexOf")}}, {{jsxref("Array.prototype.every", "every")}}, {{jsxref("Array.prototype.some", "some")}}, {{jsxref("Array.prototype.forEach", "forEach")}}, {{jsxref("Array.prototype.map", "map")}}, {{jsxref("Array.prototype.filter", "filter")}}, {{jsxref("Array.prototype.reduce", "reduce")}}, {{jsxref("Array.prototype.reduceRight", "reduceRight")}}
{{SpecName('ES6', '#sec-array-objects', 'Array')}}{{Spec2('ES6')}}加入新方法:{{jsxref("Array.from")}}, {{jsxref("Array.of")}}, {{jsxref("Array.prototype.find", "find")}}, {{jsxref("Array.prototype.findIndex", "findIndex")}}, {{jsxref("Array.prototype.fill", "fill")}}, {{jsxref("Array.prototype.copyWithin", "copyWithin")}}
{{SpecName('ES7', '#sec-array-objects', 'Array')}}{{Spec2('ES7')}}加入新方法:{{jsxref("Array.prototype.includes()")}}
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.Array")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/indexof/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/indexof/index.html new file mode 100644 index 0000000000..ff6bbdba76 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/indexof/index.html @@ -0,0 +1,260 @@ +--- +title: Array.prototype.indexOf() +slug: Web/JavaScript/Reference/Global_Objects/Array/indexOf +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/indexOf +--- +
{{JSRef}}
+ +

indexOf() 方法會回傳給定元素於陣列中第一個被找到之索引,若不存在於陣列中則回傳 -1。

+ +
+

備註:若是調用字串的方法,請參閱 {{jsxref("String.prototype.indexOf()")}}。

+
+ +
{{EmbedInteractiveExample("pages/js/array-indexof.html")}}
+ + + +

語法

+ +
arr.indexOf(searchElement[, fromIndex])
+ +

參數

+ +
+
searchElement
+
欲在陣列中搜尋的元素。
+
fromIndex {{optional_inline}}
+
陣列中搜尋的起始索引。若這個索引值大於或等於陣列長度,會直接回傳 -1,意即不會在陣列中搜尋。如果索引值是一個負數,會從陣列的最後一個往回算,最後一個的索引值為 -1,以此類推。注意:儘管往回算,但依然會從左往右全部搜尋。如果負數索引值在回頭計算之後仍然小於 0,則會從左往右全部搜尋。 這個參數的預設值為 0(即搜尋整個陣列)。
+
+ +

回傳值

+ +

在陣列中找到的第一個元素索引值;沒找到則為 -1

+ +

說明

+ +

indexOf()嚴格相等(strict equality,===的方式比較陣列中的元素與 searchElement 是否相等。

+ +

範例

+ +

使用 indexOf()

+ +

下面範例使用indexOf()來定位在陣列中的值。

+ +
var array = [2, 9, 9];
+array.indexOf(2);     // 0
+array.indexOf(7);     // -1
+array.indexOf(9, 2);  // 2
+array.indexOf(2, -1); // -1
+array.indexOf(2, -3); // 0
+
+ +

尋找該元素所有出現在陣列中的位置

+ +
var indices = [];
+var array = ['a', 'b', 'a', 'c', 'a', 'd'];
+var element = 'a';
+var idx = array.indexOf(element);
+while (idx != -1) {
+  indices.push(idx);
+  idx = array.indexOf(element, idx + 1);
+}
+console.log(indices);
+// [0, 2, 4]
+
+ +

尋找元素是否存在於陣列中,若沒有則加入到陣列裡。

+ +
function updateVegetablesCollection (veggies, veggie) {
+    if (veggies.indexOf(veggie) === -1) {
+        veggies.push(veggie);
+        console.log('New veggies collection is : ' + veggies);
+    } else if (veggies.indexOf(veggie) > -1) {
+        console.log(veggie + ' already exists in the veggies collection.');
+    }
+}
+
+var veggies = ['potato', 'tomato', 'chillies', 'green-pepper'];
+
+updateVegetablesCollection(veggies, 'spinach');
+// New veggies collection is : potato,tomato,chillies,green-pepper,spinach
+updateVegetablesCollection(veggies, 'spinach');
+// spinach already exists in the veggies collection.
+
+ +

Polyfill

+ +

indexOf() was added to the ECMA-262 standard in the 5th edition; as such it may not be present in all browsers. You can work around this by utilizing the following code at the beginning of your scripts. This will allow you to use indexOf() when there is still no native support. This algorithm matches the one specified in ECMA-262, 5th edition, assuming {{jsxref("Global_Objects/TypeError", "TypeError")}} and {{jsxref("Math.abs()")}} have their original values.

+ +

 

+ +
if (!Array.prototype.indexOf) {
+  Array.prototype.indexOf = function indexOf(member, startFrom) {
+    /*
+    In non-strict mode, if the `this` variable is null or undefined, then it is
+    set to the window object. Otherwise, `this` is automatically converted to an
+    object. In strict mode, if the `this` variable is null or undefined, a
+    `TypeError` is thrown.
+    */
+    if (this == null) {
+      throw new TypeError("Array.prototype.indexOf() - can't convert `" + this + "` to object");
+    }
+
+    var
+      index = isFinite(startFrom) ? Math.floor(startFrom) : 0,
+      that = this instanceof Object ? this : new Object(this),
+      length = isFinite(that.length) ? Math.floor(that.length) : 0;
+
+    if (index >= length) {
+      return -1;
+    }
+
+    if (index < 0) {
+      index = Math.max(length + index, 0);
+    }
+
+    if (member === undefined) {
+      /*
+        Since `member` is undefined, keys that don't exist will have the same
+        value as `member`, and thus do need to be checked.
+      */
+      do {
+        if (index in that && that[index] === undefined) {
+          return index;
+        }
+      } while (++index < length);
+    } else {
+      do {
+        if (that[index] === member) {
+          return index;
+        }
+      } while (++index < length);
+    }
+
+    return -1;
+  };
+}
+ +

 

+ +

However, if you are more interested in all the little technical bits defined by the ECMA standard, and are less concerned about performance or conciseness, then you may find this more descriptive polyfill to be more usefull.

+ +
// Production steps of ECMA-262, Edition 5, 15.4.4.14
+// Reference: http://es5.github.io/#x15.4.4.14
+if (!Array.prototype.indexOf) {
+  Array.prototype.indexOf = function(searchElement, fromIndex) {
+
+    var k;
+
+    // 1. Let o be the result of calling ToObject passing
+    //    the this value as the argument.
+    if (this == null) {
+      throw new TypeError('"this" is null or not defined');
+    }
+
+    var o = Object(this);
+
+    // 2. Let lenValue be the result of calling the Get
+    //    internal method of o with the argument "length".
+    // 3. Let len be ToUint32(lenValue).
+    var len = o.length >>> 0;
+
+    // 4. If len is 0, return -1.
+    if (len === 0) {
+      return -1;
+    }
+
+    // 5. If argument fromIndex was passed let n be
+    //    ToInteger(fromIndex); else let n be 0.
+    var n = fromIndex | 0;
+
+    // 6. If n >= len, return -1.
+    if (n >= len) {
+      return -1;
+    }
+
+    // 7. If n >= 0, then Let k be n.
+    // 8. Else, n<0, Let k be len - abs(n).
+    //    If k is less than 0, then let k be 0.
+    k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);
+
+    // 9. Repeat, while k < len
+    while (k < len) {
+      // a. Let Pk be ToString(k).
+      //   This is implicit for LHS operands of the in operator
+      // b. Let kPresent be the result of calling the
+      //    HasProperty internal method of o with argument Pk.
+      //   This step can be combined with c
+      // c. If kPresent is true, then
+      //    i.  Let elementK be the result of calling the Get
+      //        internal method of o with the argument ToString(k).
+      //   ii.  Let same be the result of applying the
+      //        Strict Equality Comparison Algorithm to
+      //        searchElement and elementK.
+      //  iii.  If same is true, return k.
+      if (k in o && o[k] === searchElement) {
+        return k;
+      }
+      k++;
+    }
+    return -1;
+  };
+}
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.14', 'Array.prototype.indexOf')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.indexof', 'Array.prototype.indexOf')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.indexof', 'Array.prototype.indexOf')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.indexOf")}}

+
+ +

相容性備註

+ + + +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/isarray/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/isarray/index.html new file mode 100644 index 0000000000..f610cd1f54 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/isarray/index.html @@ -0,0 +1,134 @@ +--- +title: Array.isArray() +slug: Web/JavaScript/Reference/Global_Objects/Array/isArray +tags: + - Array + - ECMAScript5 + - JavaScript + - Method + - Reference + - polyfill + - 方法 + - 陣列 +translation_of: Web/JavaScript/Reference/Global_Objects/Array/isArray +--- +
{{JSRef}}
+ +

Array.isArray() 函式會檢查傳入的值是否為一個 {{jsxref("Array")}}。

+ +
Array.isArray([1, 2, 3]);  // true
+Array.isArray({foo: 123}); // false
+Array.isArray('foobar');   // false
+Array.isArray(undefined);  // false
+
+ +

語法

+ +
Array.isArray(obj)
+ +

參數

+ +
+
obj
+
要檢查的物件。
+
+ +

回傳值

+ +

若物件為 {{jsxref("Array")}} 回傳 true;否則回傳 false

+ +

描述

+ +

檢查傳入的物件是否為陣列({{jsxref("Array")}}),如果是便回傳 true,否則回傳 false

+ +

更多細節請參考 “Determining with absolute accuracy whether or not a JavaScript object is an array”

+ +

範例

+ +
// 下方都回傳 true
+Array.isArray([]);
+Array.isArray([1]);
+Array.isArray(new Array());
+Array.isArray(new Array('a', 'b', 'c', 'd'));
+Array.isArray(new Array(3));
+// 小細節:Array.prototype 本身是陣列:
+Array.isArray(Array.prototype);
+
+// 下方都回傳 false
+Array.isArray();
+Array.isArray({});
+Array.isArray(null);
+Array.isArray(undefined);
+Array.isArray(17);
+Array.isArray('Array');
+Array.isArray(true);
+Array.isArray(false);
+Array.isArray({ __proto__: Array.prototype });
+
+ +

instanceof vs isArray

+ +

當檢查 Array 實例時,Array.isArray 相較於 instanceof 更加推薦,因為它可以穿透 iframes

+ +
var iframe = document.createElement('iframe');
+document.body.appendChild(iframe);
+xArray = window.frames[window.frames.length-1].Array;
+var arr = new xArray(1,2,3); // [1,2,3]
+
+// 正確地檢查陣列型態
+Array.isArray(arr);  // true
+// 有害地,因為它不能在 iframes 之間正常運作
+arr instanceof Array; // false
+
+ +

Polyfill

+ +

如果 Array.isArray() 不存在於您的環境,在其他程式碼前執行下列程式碼可建置 Array.isArray()

+ +
if (!Array.isArray) {
+  Array.isArray = function(arg) {
+    return Object.prototype.toString.call(arg) === '[object Array]';
+  };
+}
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.3.2', 'Array.isArray')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.isArray")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/join/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/join/index.html new file mode 100644 index 0000000000..0beaecebdd --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/join/index.html @@ -0,0 +1,109 @@ +--- +title: Array.prototype.join() +slug: Web/JavaScript/Reference/Global_Objects/Array/join +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/join +--- +
{{JSRef}}
+ +

join() 方法會將陣列(或一個類陣列(array-like)物件)中所有的元素連接、合併成一個字串,並回傳此字串。

+ +
{{EmbedInteractiveExample("pages/js/array-join.html")}}
+ + + +

語法

+ +
arr.join([separator])
+ +

參數

+ +
+
separator {{optional_inline}}
+
用來隔開陣列中每個元素的字串。如果必要的話,separator 會自動被轉成字串型態。如果未傳入此參數,陣列中的元素將預設用英文逗號(「,」)隔開。如果 separator 是空字串,合併後,元素間不會有任何字元。
+
+ +

回傳值

+ +

一個合併所有陣列元素的字串。假如 arr.length0,將回傳空字串。

+ +

描述

+ +

將所有陣列中的元素轉成字串型態後,連接合併成一個字串。任何 undefinednull 的元素都會被視為空字串處理。

+ +

範例

+ +

舉例四種合併用法

+ +

下方的範例中,首先宣告一個陣列—a,其中有三個元素。接著分別用:預設值、逗號、加號和空字串將陣列連接。

+ +
var a = ['Wind', 'Rain', 'Fire'];
+a.join();      // 'Wind,Rain,Fire'
+a.join(', ');  // 'Wind, Rain, Fire'
+a.join(' + '); // 'Wind + Rain + Fire'
+a.join('');    // 'WindRainFire'
+ +

合併一個類陣列(array-like)物件

+ +

下方的範例將合併一個類陣列(array-like)物件(arguments),藉由 {{jsxref("Function.prototype.call")}} 來呼叫 Array.prototype.join

+ +
function f(a, b, c) {
+  var s = Array.prototype.join.call(arguments);
+  console.log(s); // '1,a,true'
+}
+f(1, 'a', true);
+//expected output: "1,a,true"
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態註解
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.4.4.5', 'Array.prototype.join')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.join', 'Array.prototype.join')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.join', 'Array.prototype.join')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.join")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/keys/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/keys/index.html new file mode 100644 index 0000000000..fa71299ecb --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/keys/index.html @@ -0,0 +1,76 @@ +--- +title: Array.prototype.keys() +slug: Web/JavaScript/Reference/Global_Objects/Array/keys +tags: + - Array + - ECMAScript 2015 + - Iterator + - JavaScript + - Method + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/keys +--- +
{{JSRef}}
+ +

keys() 方法會回傳一個包含陣列中的每一個索引之鍵(keys)的新 Array Iterator 物件。

+ +
{{EmbedInteractiveExample("pages/js/array-keys.html")}}
+ + + +

語法

+ +
arr.keys()
+ +

回傳值

+ +

一個新的 {{jsxref("Array")}} 迭代器(iterator)物件。

+ +

範例

+ +

鍵迭代器不會乎略陣列中的空元素

+ +
var arr = ['a', , 'c'];
+var sparseKeys = Object.keys(arr);
+var denseKeys = [...arr.keys()];
+console.log(sparseKeys); // ['0', '2']
+console.log(denseKeys);  // [0, 1, 2]
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-array.prototype.keys', 'Array.prototype.keys')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.keys', 'Array.prototype.keys')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.keys")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/lastindexof/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/lastindexof/index.html new file mode 100644 index 0000000000..930b45d3e3 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/lastindexof/index.html @@ -0,0 +1,168 @@ +--- +title: Array.prototype.lastIndexOf() +slug: Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf +--- +
{{JSRef}}
+ +

lastIndexOf() 方法會回傳給定元素於陣列中最後一個被找到之索引,若不存在於陣列中則回傳 -1。搜尋的方向為由陣列尾部向後(即向前)尋找,啟始於 fromIndex

+ +
{{EmbedInteractiveExample("pages/js/array-lastindexof.html")}}
+ + + +

語法

+ +
arr.lastIndexOf(searchElement)
+arr.lastIndexOf(searchElement, fromIndex)
+
+ +

參數

+ +
+
searchElement
+
欲在陣列中搜尋的元素。
+
fromIndex {{optional_inline}}
+
要由陣列尾部向後(即向前)搜尋的啟始索引。預設為陣列長度減一(arr.length - 1),即會搜尋整個陣列。假如索引大於等於陣列長度,會搜尋整個陣列。如果索引值為負數,會從陣列的最後一個往回算,最後一個的索引值為 -1,以此類推。注意:儘管往回算,但依然會從右往左全部搜尋。如果負數索引值在回頭計算之後仍然小於 0,將會回傳 -1,即不會搜尋陣列。
+
+ +

回傳值

+ +

在陣列中找到的最後一個元素索引值;沒找到則為 -1

+ +

描述

+ +

lastIndexOf compares searchElement to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator).

+ +

範例

+ +

使用 lastIndexOf

+ +

The following example uses lastIndexOf to locate values in an array.

+ +
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 {{jsxref("Array.prototype.push", "push")}} to add them to another array as they are found.

+ +
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 {{jsxref("Array.prototype.indexOf", "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 {{jsxref("Object")}}, {{jsxref("TypeError")}}, {{jsxref("Number")}}, {{jsxref("Math.floor")}}, {{jsxref("Math.abs")}}, and {{jsxref("Math.min")}} have their original values.

+ +
// 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.

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.15', 'Array.prototype.lastIndexOf')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.lastindexof', 'Array.prototype.lastIndexOf')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.lastindexof', 'Array.prototype.lastIndexOf')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.lastIndexOf")}}

+
+ +

相容性備註

+ + + +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/length/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/length/index.html new file mode 100644 index 0000000000..453564d528 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/length/index.html @@ -0,0 +1,131 @@ +--- +title: Array.length +slug: Web/JavaScript/Reference/Global_Objects/Array/length +translation_of: Web/JavaScript/Reference/Global_Objects/Array/length +--- +
{{JSRef}}
+ +

length 為Array物件的屬性 ,可供設定或回傳該陣列實體中包含的元素個數。其值必為一大於零、32位元、且恆大於該陣列最大索引數的正整數。

+ +
var items = ['shoes', 'shirts', 'socks', 'sweaters'];
+items.length;
+
+// returns 4
+ +

描述

+ +

length 屬性的值必為一正整數,其值必介於 0 ~ 232 (不包含)之間.

+ +
var namelistA = new Array(4294967296); //232 = 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 ~ 232 -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 與數值屬性的關係

+ +

{{js_property_attributes(1, 0, 0)}}

+ +
+ +
+ +

範例

+ +

對陣列進行迭代處理

+ +

以下範例中, 陣列 numbers 透過 length 屬性進行迭代操作,並將其內容值加倍。

+ +
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。

+ +
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
+
+ +

規格

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.4.5.2', 'Array.length')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-properties-of-array-instances-length', 'Array.length')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-properties-of-array-instances-length', 'Array.length')}}{{Spec2('ESDraft')}}
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.length")}}

+
+ +

其他

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/map/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/map/index.html new file mode 100644 index 0000000000..d1838ce6ae --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/map/index.html @@ -0,0 +1,320 @@ +--- +title: Array.prototype.map() +slug: Web/JavaScript/Reference/Global_Objects/Array/map +tags: + - Array + - ECMAScript 5 + - ECMAScript6 + - JavaScript + - Method + - Prototype + - Reference + - polyfill + - 陣列 +translation_of: Web/JavaScript/Reference/Global_Objects/Array/map +--- +
{{JSRef}}
+ +

map() 方法會建立一個新的陣列,其內容為原陣列的每一個元素經由回呼函式運算後所回傳的結果之集合。

+ +
{{EmbedInteractiveExample("pages/js/array-map.html")}}
+ + + +

語法

+ +
let new_array = arr.map(function callback( currentValue[, index[, array]]) {
+    // return element for new_array
+}[, thisArg])
+
+ +

參數

+ +
+
callback
+
+

呼叫 arr 所有元素的回呼函式。新數值會在每次執行 callback 時加到 new_array

+ +

callback 函式可傳入以下三個參數:

+ +
+
+
currentValue
+
原陣列目前所迭代處理中的元素。
+
index{{optional_inline}}
+
原陣列目前所迭代處理中的元素之索引。
+
array{{optional_inline}}
+
呼叫 map 方法的陣列。
+
+
+
thisArg{{optional_inline}}
+
選擇性的參數。執行 callback 回呼函式的 this 值。
+
+ +

回傳值

+ +

一個所有元素皆為回呼函式運算結果的新陣列。

+ +

描述

+ +

map 會將所有陣列中的元素依序分別傳入一次callback 函式當中,並以此回呼函式每一次被呼叫的回傳值來建構一個新的陣列。callback 函式只會於陣列目前迭代之索引有指派值時(包含{{jsxref("undefined")}})被調用,而在該陣列索引沒有元素時(即未被設定的索引:已被刪除或從未被賦值)並不會呼叫回呼函式。

+ +

並不能呼叫以下元素:

+ + + +

什麼時候不要用 map()

+ +

因為 map 會建立新的陣列,如果在不想建立新陣列時使用該方法,就會變成反模式(anti-pattern):這種情況下,要使用 forEachfor-of

+ +

以下情況不應該使用 map

+ +
    +
  1. 不使用回傳的新陣列,
  2. +
  3. 或/且不需要回傳新陣列。
  4. +
+ +

callback 函式於被調用時會傳入三個參數:元素值、元素之索引、以及被迭代的陣列物件。

+ +

若有提供 thisArg 參數予 map 方法,thisArg 將會被當作回呼函式的 this 值,否則 this 會是 {{jsxref("undefined")}}。callback 的最終 this 值是依據函式的 this 規則來決定。

+ +

map 不會修改呼叫它的原始陣列(雖然在 callback 執行時有可能會這麼做)。

+ +

map 方法所回傳之新陣列的範圍,於 callback 函式第一次被調用之前就已經被設定。而在呼叫 map 之後才加至原始陣列中的元素,將不會傳入 callback 當中。假如原始陣列中元素的值改變了,則 callback 得到此元素的值將會是 map 傳入元素當下的值。而在呼叫 map 之後、且於被 map 傳入 callback 之前就被刪除的原始陣列元素,並不會被 map 迭代到。
+
+ 依據規範中定義的演算法,若呼叫 map 方法的原始陣列為一稀疏(sparse)陣列,則回傳的新陣列也會是在同樣索引中留空的稀疏陣列。

+ +

範例

+ +

把一個數字陣列轉換成對應的開根號後的數字陣列

+ +

以下的程式碼把一個數字陣列(array of numbers) 轉換成一個 新的以該數字陣列裡的一個個數做開根號計算的數字陣列.

+ +
var numbers = [1, 4, 9];
+var roots = numbers.map(Math.sqrt); //map會return一個新的array
+// roots 現在是 [1, 2, 3]
+/* numbers 還是 [1, 4, 9],這證明了 map() 不會去變動到 numbers 的值,
+   map 內部是做了 immutable 的機制,Array.prototype 底下的這些高階函式
+   大多都具有這樣函數式編程裡非常注重的特性 - immutable,不會去改變資料
+   來源本身原有的值
+*/ 
+ +

使用 map 將陣列中的物件變更格式

+ +

以下程式碼取出一陣列,將其中物件變更格式後建立為一個新的陣列並傳回。

+ +
var kvArray = [{key: 1, value: 10},
+               {key: 2, value: 20},
+               {key: 3, value: 30}];
+
+var reformattedArray = kvArray.map(function(obj) {
+   var rObj = {};
+   rObj[obj.key] = obj.value;
+   return rObj;
+});
+
+// reformattedArray 現在是 [{1: 10}, {2: 20}, {3: 30}],
+
+// kvArray 仍然是:
+// [{key: 1, value: 10},
+//  {key: 2, value: 20},
+//  {key: 3, value: 30}]
+
+ +

使用帶參數的函式將一數字陣列進行對應

+ +

以下程式碼示範如何使用帶有一個參數的函式來操作 map。這個參數會自動地逐一取出原始陣列中各個元素來使用。

+ +
var numbers = [1, 4, 9];
+var doubles = numbers.map(function(num) {
+  return num * 2;
+});
+
+// doubles 現在是 [2, 8, 18]
+// numbers 仍然是 [1, 4, 9]
+
+ +

使用 map 於泛型陣列

+ +

以下範例示範如何將一個 {{jsxref("String")}} 陣列轉換為 byte 陣列:

+ +
var map = Array.prototype.map;
+var a = map.call('Hello World', function(x) {
+  return x.charCodeAt(0);
+});
+// a 現在等於 [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
+
+ +

使用 map 遍歷 querySelectorAll

+ +

本範例將展示如何遍歷由 querySelectorAll 所產生的物件。我們將得到所有的選項、並印在主控台上:

+ +
var elems = document.querySelectorAll('select option:checked');
+var values = Array.prototype.map.call(elems, function(obj) {
+  return obj.value;
+});
+
+ +

如果用上 {{jsxref("Array.from()")}} 方法的話會更簡單。

+ +

棘手的範例

+ +

(透過連結的部落格啟發)

+ +

透過一個(被遍歷元素的)參數叫出回調是個常見的用法。有些函式也常常在含有其他可選參數的情況下,使用上一個參數。這種行為常常會給人帶來困惑。

+ +
// Consider:
+['1', '2', '3'].map(parseInt);
+// 以為會是 [1, 2, 3] 嗎
+// 其實是 [1, NaN, NaN]
+
+// parseInt 通常只用上一個參數 argument,但他其實用了兩個:
+// 第一個是表達式,第二個則是進位數。
+// 對該回呼函式來說 Array.prototype.map 帶了三個參數:
+// 元素、索引、陣列
+// 第三個參數會被 parseInt 忽略,但它可不會忽略第二個,
+// 因此可能造成困惑。可以去看上面提到的部落格文章以獲知詳情。
+
+function returnInt(element) {
+  return parseInt(element, 10);
+}
+
+['1', '2', '3'].map(returnInt); // [1, 2, 3]
+// Actual result is an array of numbers (as expected)
+
+// Same as above, but using the concise arrow function syntax
+['1', '2', '3'].map( str => parseInt(str) );
+
+// A simpler way to achieve the above, while avoiding the "gotcha":
+['1', '2', '3'].map(Number); // [1, 2, 3]
+// but unlike `parseInt` will also return a float or (resolved) exponential notation:
+['1.1', '2.2e2', '3e300'].map(Number); // [1.1, 220, 3e+300]
+
+ +

Polyfill

+ +

map was added to the ECMA-262 standard in the 5th edition; as such it may not be present in all implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of map in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming {{jsxref("Object")}}, {{jsxref("TypeError")}}, and {{jsxref("Array")}} have their original values and that callback.call evaluates to the original value of {{jsxref("Function.prototype.call")}}.

+ +
// Production steps of ECMA-262, Edition 5, 15.4.4.19
+// Reference: http://es5.github.io/#x15.4.4.19
+if (!Array.prototype.map) {
+
+  Array.prototype.map = function(callback/*, thisArg*/) {
+
+    var T, A, k;
+
+    if (this == null) {
+      throw new TypeError('this is null or not defined');
+    }
+
+    // 1. Let O be the result of calling ToObject passing the |this|
+    //    value as the argument.
+    var O = Object(this);
+
+    // 2. Let lenValue be the result of calling the Get internal
+    //    method of O with the argument "length".
+    // 3. Let len be ToUint32(lenValue).
+    var len = O.length >>> 0;
+
+    // 4. If IsCallable(callback) is false, throw a TypeError exception.
+    // See: http://es5.github.com/#x9.11
+    if (typeof callback !== 'function') {
+      throw new TypeError(callback + ' is not a function');
+    }
+
+    // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
+    if (arguments.length > 1) {
+      T = arguments[1];
+    }
+
+    // 6. Let A be a new array created as if by the expression new Array(len)
+    //    where Array is the standard built-in constructor with that name and
+    //    len is the value of len.
+    A = new Array(len);
+
+    // 7. Let k be 0
+    k = 0;
+
+    // 8. Repeat, while k < len
+    while (k < len) {
+
+      var kValue, mappedValue;
+
+      // a. Let Pk be ToString(k).
+      //   This is implicit for LHS operands of the in operator
+      // b. Let kPresent be the result of calling the HasProperty internal
+      //    method of O with argument Pk.
+      //   This step can be combined with c
+      // c. If kPresent is true, then
+      if (k in O) {
+
+        // i. Let kValue be the result of calling the Get internal
+        //    method of O with argument Pk.
+        kValue = O[k];
+
+        // ii. Let mappedValue be the result of calling the Call internal
+        //     method of callback with T as the this value and argument
+        //     list containing kValue, k, and O.
+        mappedValue = callback.call(T, kValue, k, O);
+
+        // iii. Call the DefineOwnProperty internal method of A with arguments
+        // Pk, Property Descriptor
+        // { Value: mappedValue,
+        //   Writable: true,
+        //   Enumerable: true,
+        //   Configurable: true },
+        // and false.
+
+        // In browsers that support Object.defineProperty, use the following:
+        // Object.defineProperty(A, k, {
+        //   value: mappedValue,
+        //   writable: true,
+        //   enumerable: true,
+        //   configurable: true
+        // });
+
+        // For best browser support, use the following:
+        A[k] = mappedValue;
+      }
+      // d. Increase k by 1.
+      k++;
+    }
+
+    // 9. return A
+    return A;
+  };
+}
+
+ +

規範

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-array.prototype.map', 'Array.prototype.map')}}
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.map")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/of/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/of/index.html new file mode 100644 index 0000000000..31118bbeb6 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/of/index.html @@ -0,0 +1,98 @@ +--- +title: Array.of() +slug: Web/JavaScript/Reference/Global_Objects/Array/of +tags: + - Array + - ECMAScript 2015 + - JavaScript + - Method + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/Array/of +--- +
{{JSRef}}
+ +

Array.of() 方法會由引數(arguments)的數量來建立一個新的 Array 實體,而不管引數的數量或類型為何。

+ +

Array.of()Array 建構式之間的不同在於如何處理整數引數:Array.of(7) 會建立一個擁有單個元素—7—的陣列,而 Array(7) 會建立一個 length 屬性值為 7 的空陣列(註:這意味著這個陣列有 7 個空缺欄位(empty slots),而非 7 個值為 undefined 的欄位)。

+ +
Array.of(7);       // [7]
+Array.of(1, 2, 3); // [1, 2, 3]
+
+Array(7);          // [ , , , , , , ]
+Array(1, 2, 3);    // [1, 2, 3]
+
+ +

語法

+ +
Array.of(element0[, element1[, ...[, elementN]]])
+ +

參數

+ +
+
elementN
+
要用來成為新建立之陣列的元素。
+
+ +

回傳值

+ +

一個新的 {{jsxref("Array")}} 實體。

+ +

描述

+ +

此函式是 ECMAScript 2015 標準的一部分。更多資訊可參考 Array.of and Array.from proposal 以及 Array.of polyfill

+ +

範例

+ +
Array.of(1);         // [1]
+Array.of(1, 2, 3);   // [1, 2, 3]
+Array.of(undefined); // [undefined]
+
+ +

Polyfill

+ +

若所有執行環境沒有原生支援,可以在其他程式之前先執行以下程式碼來建立 Array.of()

+ +
if (!Array.of) {
+  Array.of = function() {
+    return Array.prototype.slice.call(arguments);
+  };
+}
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-array.of', 'Array.of')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.of', 'Array.of')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.of")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/pop/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/pop/index.html new file mode 100644 index 0000000000..3124fa26bc --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/pop/index.html @@ -0,0 +1,98 @@ +--- +title: Array.prototype.pop() +slug: Web/JavaScript/Reference/Global_Objects/Array/pop +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/pop +--- +
{{JSRef}}
+ +

pop() 方法會移除並回傳陣列的最後一個元素。此方法會改變陣列的長度。

+ +
{{EmbedInteractiveExample("pages/js/array-pop.html")}}
+ + + +

語法

+ +
arr.pop()
+ +

回傳值

+ +

自陣列中移除的元素;若陣列為空,則為 {{jsxref("undefined")}}。

+ +

描述

+ +

pop 方法會移除陣列中的最後一個元素,並將該值回傳給呼叫者。

+ +

pop 方法被刻意設計為具通用性;此方法可以藉由 {{jsxref("Function.call", "called", "", 1)}} 或 {{jsxref("Function.apply", "applied", "", 1)}} 應用於類似陣列的物件上。若欲應用此方法的物件不包含代表一系列啟始為零之數字屬性序列長度的 length 屬性,可能是不具任何意義的行為。

+ +

如果於空陣列呼叫 pop(),將會回傳 {{jsxref("undefined")}}。

+ +

範例

+ +

移除陣列的最後一個元素

+ +

下面的程式碼為一個包含四個元素的 myFish 陣列,接著移除此陣列的最後一個元素。

+ +
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
+
+var popped = myFish.pop();
+
+console.log(myFish); // ['angel', 'clown', 'mandarin' ]
+
+console.log(popped); // 'sturgeon'
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.6', 'Array.prototype.pop')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.pop', 'Array.prototype.pop')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.pop', 'Array.prototype.pop')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.pop")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/push/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/push/index.html new file mode 100644 index 0000000000..a506ad15b6 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/push/index.html @@ -0,0 +1,143 @@ +--- +title: Array.prototype.push() +slug: Web/JavaScript/Reference/Global_Objects/Array/push +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference + - 陣列 +translation_of: Web/JavaScript/Reference/Global_Objects/Array/push +--- +
{{JSRef}}
+ +

push() 方法會添加一個或多個元素至陣列的末端,並且回傳陣列的新長度。

+ +
{{EmbedInteractiveExample("pages/js/array-push.html")}}
+ + + +

語法

+ +
arr.push(element1[, ...[, elementN]])
+ +

參數

+ +
+
elementN
+
欲添加至陣列末端的元素。
+
+ +

回傳值

+ +

呼叫此方法之物件的新 {{jsxref("Array.length", "length")}} 屬性值。

+ +

描述

+ +

push 方法會將一或多個值加入至一個陣列中。

+ +

push 方法被刻意設計為具通用性;此方法可以藉由 {{jsxref("Function.call", "call()")}} 或 {{jsxref("Function.apply", "apply()")}} 應用於類似陣列的物件上。push 方法憑借著物件的 length 屬性來判斷從何處開始插入給定的值。如果 length 屬性無法被轉為數字,則索引值會使用 0。這包括了 length 可能不存在的狀況,在這個情況下 length 屬性也將被建立於物件中。

+ +

唯一的原生類陣列(array-like)物件為{{jsxref("Global_Objects/String", "字串", "", 1)}},但他們不適合用於此方法,因為字串是不可變的(immutable)。

+ +

範例

+ +

將複數個元素添加至陣列

+ +

以下的程式碼會建立含有兩個元素的陣列 sports,接著再增加兩個元素至陣列中。新的長度以變數 total 表示。

+ +
var sports = ['soccer', 'baseball'];
+var total = sports.push('football', 'swimming');
+
+console.log(sports); // ['soccer', 'baseball', 'football', 'swimming']
+console.log(total);  // 4
+
+ +

合併兩個陣列

+ +

這個範例使用 {{jsxref("Function.apply", "apply()")}} 自第二個陣列中增加所有的元素至第一個陣列。

+ +

如果第二個陣列(範例中的 moreVegs)非常大,就不要使用這個方法。因為一個函式能取得的參數之最大數量是受到實作限制的。詳細請參閱 {{jsxref("Function.apply", "apply()")}}。

+ +
var vegetables = ['parsnip', 'potato'];
+var moreVegs = ['celery', 'beetroot'];
+
+// Merge the second array into the first one
+// Equivalent to vegetables.push('celery', 'beetroot');
+Array.prototype.push.apply(vegetables, moreVegs);
+
+console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot']
+
+ +

以類陣列(array-like)的方式操作物件

+ +

正如上面所提到的,push 被刻意設計為具通用性,我們可以善用這個優勢來處理物件。Array.prototype.push 可以在物件上運作良好,如本範例所示。請注意,我們不會建立一個陣列來儲存收集到的物件。相反地,我們將物件集合(collection)儲存於物件自己身上,並使用 call 來呼叫Array.prototype.push 使其認為我們正在處理一個陣列,讓方法可以繼續運作。感謝 JavaScript 允許我們使用這個方式去執行上下文。

+ +
var obj = {
+    length: 0,
+
+    addElem: function addElem(elem) {
+        // obj.length is automatically incremented
+        // every time an element is added.
+        [].push.call(this, elem);
+    }
+};
+
+// Let's add some empty objects just to illustrate.
+obj.addElem({});
+obj.addElem({});
+console.log(obj.length);
+// → 2
+
+ +

請注意雖然 obj 不是一個陣列,但 push 方法成功增加了 objlength 屬性,就像我們在處理一個真正的陣列一樣。

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態註解
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.7', 'Array.prototype.push')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.push', 'Array.prototype.push')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.push', 'Array.prototype.push')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器支援度

+ +
+ + +

{{Compat("javascript.builtins.Array.push")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/reduce/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/reduce/index.html new file mode 100644 index 0000000000..1f943d8dfa --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/reduce/index.html @@ -0,0 +1,472 @@ +--- +title: Array.prototype.reduce() +slug: Web/JavaScript/Reference/Global_Objects/Array/Reduce +tags: + - Array + - ECMAScript 5 + - JavaScript + - Method + - Prototype + - Reduce + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/Reduce +--- +
{{JSRef}}
+ +

reduce() 方法將一個累加器及陣列中每項元素(由左至右)傳入回呼函式,將陣列化為單一值。

+ +
{{EmbedInteractiveExample("pages/js/array-reduce.html")}}
+ +

語法

+ +
arr.reduce(callback[accumulator, currentValue, currentIndex, array], initialValue)
+ +

參數

+ +
+
callback
+
用於處理陣列中每個元素的函式,可傳入四個參數: +
+
accumulator
+
用來累積回呼函式回傳值的累加器(accumulator)或 initialValue(若有提供的話,詳如下敘)。累加器是上一次呼叫後,所回傳的累加數值。
+
currentValue
+
原陣列目前所迭代處理中的元素。
+
currentIndex{{optional_inline}}
+
原陣列目前所迭代處理中的元素之索引。若有傳入 initialValue,則由索引 0 之元素開始,若無則自索引 1 之元素開始。
+
array{{optional_inline}}
+
呼叫 reduce() 方法的陣列。
+
+
+
initialValue{{optional_inline}}
+
於第一次呼叫 callback 時要傳入的累加器初始值。若沒有提供初始值,則原陣列的第一個元素將會被當作初始的累加器。假如於一個空陣列呼叫 reduce() 方法且沒有提供累加器初始值,將會發生錯誤。
+
+ +

回傳值

+ +

簡化後的結果值。

+ +

描述

+ +

reduce() 會對每一個目前迭代到的陣列元素(除了空值以外)執行 callback 函式,回呼函式會接收四個參數:

+ + + +

當回呼函式第一次被呼叫時,accumulatorcurrentValue 的值可能為兩種不同的狀況:若在呼叫 reduce() 時有提供 initialValue,則 accumulator 將會等於 initialValue,且 currentValue 會等於陣列中的第一個元素值;若沒有提供 initialValue,則 accumulator 會等於陣列的第一個元素值,且 currentValue 將會等於陣列的第二個元素值。

+ +
+

備註:假如 initialValue 未被提供,reduce() 將會跳過第一個陣列索引,從陣列索引 1 開始執行回呼函式。若有提供 initialValue,則會由陣列索引 0 開始執行。

+
+ +

若陣列為空且沒有提供 initialValue,將會拋出 {{jsxref("TypeError")}}。假如陣列只有一個元素(無論其索引位置為何)並且沒有提供 initialValue,或如果提供了 initialValue 但陣列為空,則此唯一的值將會被直接回傳而不會呼叫 callback 函式

+ +

提供累加器初始值通常較為安全,因為在沒有傳入 initialValue 的情況下會有三種可能的輸出結果,如下列範例:

+ +
var maxCallback = ( acc, cur ) => Math.max( acc.x, cur.x );
+var maxCallback2 = ( max, cur ) => Math.max( max, cur );
+
+// reduce() without initialValue
+[ { x: 22 }, { x: 42 } ].reduce( maxCallback ); // 42
+[ { x: 22 }            ].reduce( maxCallback ); // { x: 22 }
+[                      ].reduce( maxCallback ); // TypeError
+
+// map/reduce; better solution, also works for empty or larger arrays
+[ { x: 22 }, { x: 42 } ].map( el => el.x )
+                        .reduce( maxCallback2, -Infinity );
+
+ +

reduce() 如何運作

+ +

假設 reduce() 以下例方式使用:

+ +
[0, 1, 2, 3, 4].reduce(
+  function (
+    accumulator,currentValue,
+    currentIndex,
+    array
+  ) {
+    return accumulator + currentValue;
+  }
+);
+
+ +

所傳入的回呼函式將被呼叫四次,所傳入的參數與回傳值如下所示:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
callbackaccumulatorcurrentValuecurrentIndexarrayreturn value
first call011[0, 1, 2, 3, 4]1
second call122[0, 1, 2, 3, 4]3
third call333[0, 1, 2, 3, 4]6
fourth call644[0, 1, 2, 3, 4]10
+ +

reduce() 的最終回傳值將會是最後一次呼叫回呼函式的回傳值 (10)。

+ +

你也可以傳入一個{{jsxref("Functions/Arrow_functions", "箭頭函式","",1)}}來替代一個完整的函式。下方的程式碼執行的結果將與前述例子相同。

+ +
[0, 1, 2, 3, 4].reduce( (prev, curr) => prev + curr );
+
+ +

如果你有提供第二個參數值給 reduce(),執行的結果如下:

+ +
[0, 1, 2, 3, 4].reduce(
+  (accumulator, currentValue, currentIndex, array) => {
+    return accumulator + currentValue;
+  },
+  10
+);
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
callbackaccumulatorcurrentValuecurrentIndexarrayreturn value
first call1000[0, 1, 2, 3, 4]10
second call1011[0, 1, 2, 3, 4]11
third call1122[0, 1, 2, 3, 4]13
fourth call1333[0, 1, 2, 3, 4]16
fifth call1644[0, 1, 2, 3, 4]20
+ +

reduce() 執行的結果將會是 20

+ +

範例

+ +

加總所有陣例之元素值

+ +
var sum = [0, 1, 2, 3].reduce(function (a, b) {
+  return a + b;
+}, 0);
+// sum is 6
+
+ +

另外,也可以寫成箭頭函式:

+ +
var total = [ 0, 1, 2, 3 ].reduce(
+  ( acc, cur ) => acc + cur,
+  0
+);
+ +

攤平一個多維陣列

+ +
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
+  function(a, b) {
+    return a.concat(b);
+  },
+  []
+);
+// flattened is [0, 1, 2, 3, 4, 5]
+
+ +

另外,也可以寫成箭頭函式:

+ +
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
+  ( acc, cur ) => acc.concat(cur),
+  []
+);
+
+ +

計算相同元素數量並以物件鍵值顯示

+ +
var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
+
+var countedNames = names.reduce(function (allNames, name) {
+  if (name in allNames) {
+    allNames[name]++;
+  }
+  else {
+    allNames[name] = 1;
+  }
+  return allNames;
+}, {});
+// countedNames is:
+// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
+
+ +

使用 spread 運算子與給定初始值,結合物件中的陣列元素

+ +
// friends - an array of objects
+// where object field "books" - list of favorite books
+var friends = [{
+  name: 'Anna',
+  books: ['Bible', 'Harry Potter'],
+  age: 21
+}, {
+  name: 'Bob',
+  books: ['War and peace', 'Romeo and Juliet'],
+  age: 26
+}, {
+  name: 'Alice',
+  books: ['The Lord of the Rings', 'The Shining'],
+  age: 18
+}];
+
+// allbooks - list which will contain all friends' books +
+// additional list contained in initialValue
+var allbooks = friends.reduce(function(prev, curr) {
+  return [...prev, ...curr.books];
+}, ['Alphabet']);
+
+// allbooks = [
+//   'Alphabet', 'Bible', 'Harry Potter', 'War and peace',
+//   'Romeo and Juliet', 'The Lord of the Rings',
+//   'The Shining'
+// ]
+ +

 

+ +

移除陣列中的重複項目

+ +
let arr = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4];
+let result = arr.sort().reduce((init, current) => {
+    if (init.length === 0 || init[init.length - 1] !== current) {
+        init.push(current);
+    }
+    return init;
+}, []);
+console.log(result); //[1,2,3,4,5]
+
+ +

序列執行 Promise

+ +
/**
+ * Runs promises from promise array in chained manner
+ *
+ * @param {array} arr - promise arr
+ * @return {Object} promise object
+ */
+function runPromiseInSequense(arr) {
+  return arr.reduce((promiseChain, currentPromise) => {
+    return promiseChain.then((chainedResult) => {
+      return currentPromise(chainedResult)
+        .then((res) => res)
+    })
+  }, Promise.resolve());
+}
+
+// promise function 1
+function p1() {
+  return new Promise((resolve, reject) => {
+    resolve(5);
+  });
+}
+
+// promise function 2
+function p2(a) {
+  return new Promise((resolve, reject) => {
+    resolve(a * 2);
+  });
+}
+
+// promise function 3
+function p3(a) {
+  return new Promise((resolve, reject) => {
+    resolve(a * 3);
+  });
+}
+
+const promiseArr = [p1, p2, p3];
+runPromiseInSequense(promiseArr)
+  .then((res) => {
+    console.log(res);   // 30
+  });
+
+
+ +

Polyfill

+ +
// Production steps of ECMA-262, Edition 5, 15.4.4.21
+// Reference: http://es5.github.io/#x15.4.4.21
+// https://tc39.github.io/ecma262/#sec-array.prototype.reduce
+if (!Array.prototype.reduce) {
+  Object.defineProperty(Array.prototype, 'reduce', {
+    value: function(callback /*, initialValue*/) {
+      if (this === null) {
+        throw new TypeError( 'Array.prototype.reduce ' +
+          'called on null or undefined' );
+      }
+      if (typeof callback !== 'function') {
+        throw new TypeError( callback +
+          ' is not a function');
+      }
+
+      // 1. Let O be ? ToObject(this value).
+      var o = Object(this);
+
+      // 2. Let len be ? ToLength(? Get(O, "length")).
+      var len = o.length >>> 0;
+
+      // Steps 3, 4, 5, 6, 7
+      var k = 0;
+      var value;
+
+      if (arguments.length >= 2) {
+        value = arguments[1];
+      } else {
+        while (k < len && !(k in o)) {
+          k++;
+        }
+
+        // 3. If len is 0 and initialValue is not present,
+        //    throw a TypeError exception.
+        if (k >= len) {
+          throw new TypeError( 'Reduce of empty array ' +
+            'with no initial value' );
+        }
+        value = o[k++];
+      }
+
+      // 8. Repeat, while k < len
+      while (k < len) {
+        // a. Let Pk be ! ToString(k).
+        // b. Let kPresent be ? HasProperty(O, Pk).
+        // c. If kPresent is true, then
+        //    i.  Let kValue be ? Get(O, Pk).
+        //    ii. Let accumulator be ? Call(
+        //          callbackfn, undefined,
+        //          « accumulator, kValue, k, O »).
+        if (k in o) {
+          value = callback(value, o[k], k, o);
+        }
+
+        // d. Increase k by 1.
+        k++;
+      }
+
+      // 9. Return accumulator.
+      return value;
+    }
+  });
+}
+
+ +

如果還需要支援老舊到不支援 Object.defineProperty 的 JavaScript 引擎,最好不要 polyfill Array.prototype 方法,因為你無法令其不可枚舉(non-enumerable)。

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態註解
{{SpecName('ES5.1', '#sec-15.4.4.21', 'Array.prototype.reduce()')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.
{{SpecName('ES6', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.reduce")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/reverse/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/reverse/index.html new file mode 100644 index 0000000000..d3104c28be --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/reverse/index.html @@ -0,0 +1,90 @@ +--- +title: Array.prototype.reverse() +slug: Web/JavaScript/Reference/Global_Objects/Array/reverse +tags: + - Array + - JavaScript + - Method + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/reverse +--- +
{{JSRef}}
+ +

reverse() 方法會原地(in place)反轉(reverses)一個陣列。陣列中的第一個元素變為最後一個,而最後一個元素則變成第一個。

+ +
{{EmbedInteractiveExample("pages/js/array-reverse.html")}}
+ + + +

語法

+ +
a.reverse()
+ +

回傳值

+ +

反轉後的陣列。

+ +

描述

+ +

reverse 方法將原地(in place)變換(transposes)呼叫此方法的陣列物件之元素至其顛倒的位置,改變原陣列後,並回傳此陣列之參考位址(reference)。

+ +

範例

+ +

反轉陣列中之元素

+ +

下列範例建立了一個包含三個元素的陣列 a,接著反轉此陣列。呼叫 reverse() 會回傳一個反轉後的原陣列 a 之參考。

+ +
var a = ['one', 'two', 'three'];
+var reversed = a.reverse();
+
+console.log(a);        // ['three', 'two', 'one']
+console.log(reversed); // ['three', 'two', 'one']
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
規格狀態註解
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.4.4.8', 'Array.prototype.reverse')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.reverse")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/shift/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/shift/index.html new file mode 100644 index 0000000000..269dfac4fe --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/shift/index.html @@ -0,0 +1,114 @@ +--- +title: Array.prototype.shift() +slug: Web/JavaScript/Reference/Global_Objects/Array/shift +tags: + - Array + - JavaScript + - Method + - Prototype + - shift + - 陣列 +translation_of: Web/JavaScript/Reference/Global_Objects/Array/shift +--- +
{{JSRef}}
+ +

shift() 方法會移除並回傳陣列的第一個元素。此方法會改變陣列的長度。

+ +
{{EmbedInteractiveExample("pages/js/array-shift.html")}}
+ + + +

語法

+ +
arr.shift()
+ +

回傳值

+ +

自陣列中移除的元素;若陣列為空,則為 {{jsxref("undefined")}}。

+ +

描述

+ +

shift 方法會移除並回傳陣列中索引值為零之元素(即第一個元素),並將隨後的其他索引值減一。假如 {{jsxref("Array.length", "length")}} 屬性值為 0,則會回傳 {{jsxref("undefined")}}。

+ +

shift 方法被刻意設計為具通用性;此方法可以藉由 {{jsxref("Function.call", "called", "", 1)}} 或 {{jsxref("Function.apply", "applied", "", 1)}} 應用於類似陣列的物件上。若欲應用此方法的物件不包含代表一系列啟始為零之數字屬性序列長度的 length 屬性,可能是不具任何意義的行為。

+ +

範例

+ +

自陣列中移除一個元素

+ +

以下的程式碼會印出 myFish 陣列在移除第一個元素之前跟之後的內容,也印出了被移除的元素:

+ +
var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];
+
+console.log('myFish before:', JSON.stringify(myFish));
+// myFish before: ['angel', 'clown', 'mandarin', 'surgeon']
+
+var shifted = myFish.shift();
+
+console.log('myFish after:', myFish);
+// myFish after: ['clown', 'mandarin', 'surgeon']
+
+console.log('Removed this element:', shifted);
+// Removed this element: angel
+
+ +

於 while 迴圈中使用 shift() 方法

+ +

shift() 方法常被用在 while 迴圈中的條件判斷。在下面的例子,每一次迭代都將會自陣列中移除下一個元素,直到陣列空了為止:

+ +
var names = ["Andrew", "Edward", "Paul", "Chris" ,"John"];
+
+while( (i = names.shift()) !== undefined ) {
+    console.log(i);
+}
+// Andrew, Edward, Paul, Chris, John
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.9', 'Array.prototype.shift')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.shift', 'Array.prototype.shift')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.shift', 'Array.prototype.shift')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.shift")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/slice/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/slice/index.html new file mode 100644 index 0000000000..e9cb1fb02c --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/slice/index.html @@ -0,0 +1,242 @@ +--- +title: Array.prototype.slice() +slug: Web/JavaScript/Reference/Global_Objects/Array/slice +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/slice +--- +
{{JSRef}}
+ +

slice() 方法會回傳一個新陣列物件,為原陣列選擇之 beginend(不含 end)部分的淺拷貝(shallow copy)。而原本的陣列將不會被修改。

+ +
{{EmbedInteractiveExample("pages/js/array-slice.html")}}
+ + + +

語法

+ +
arr.slice([begin[, end]])
+
+ +

參數

+ +
+
begin {{optional_inline}}
+
自哪一個索引(起始為 0)開始提取拷貝。
+
可使用負數索引,表示由陣列的最末項開始提取。slice(-2) 代表拷貝陣列中的最後兩個元素。
+
假如 begin 為 undefined,則 slice 會從索引 0 開始提取。
+
end {{optional_inline}}
+
至哪一個索引(起始為 0)之前停止提取。slice 提取但不包含至索引 end
+
舉例來說,slice(1,4) 提取了陣列中第二個元素至第四個元素前為止(元素索引 1、2 以及 3)來拷貝。
+
可使用負數索引,表示由陣列的最末項開始提取。slice(2,-1) 代表拷貝陣列中第三個元素至倒數第二個元素。
+
若省略了 end,則 slice 會提取至陣列的最後一個元素(arr.length)。
+
假如 end 大於陣列的長度,slice 會提取至陣列的最後一個元素(arr.length)。
+
+ +

回傳值

+ +

一個包含提取之元素的新陣列。

+ +

說明

+ +

slice 不會修改原本的陣列,而是回傳由原本的陣列淺層複製的元素。原始陣列的元素會按照下列規則拷貝:

+ + + +

如果添加了新的元素到另一個陣列內,則另一個不會受到影響。

+ +

範例

+ +

Return a portion of an existing array

+ +
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
+var citrus = fruits.slice(1, 3);
+
+// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
+// citrus contains ['Orange','Lemon']
+
+ +

Using slice

+ +

In the following example, slice creates a new array, newCar, from myCar. Both include a reference to the object myHonda. When the color of myHonda is changed to purple, both arrays reflect the change.

+ +
// Using slice, create newCar from myCar.
+var myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } };
+var myCar = [myHonda, 2, 'cherry condition', 'purchased 1997'];
+var newCar = myCar.slice(0, 2);
+
+// Display the values of myCar, newCar, and the color of myHonda
+//  referenced from both arrays.
+console.log('myCar = ' + JSON.stringify(myCar));
+console.log('newCar = ' + JSON.stringify(newCar));
+console.log('myCar[0].color = ' + myCar[0].color);
+console.log('newCar[0].color = ' + newCar[0].color);
+
+// Change the color of myHonda.
+myHonda.color = 'purple';
+console.log('The new color of my Honda is ' + myHonda.color);
+
+// Display the color of myHonda referenced from both arrays.
+console.log('myCar[0].color = ' + myCar[0].color);
+console.log('newCar[0].color = ' + newCar[0].color);
+
+ +

This script writes:

+ +
myCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2,
+         'cherry condition', 'purchased 1997']
+newCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2]
+myCar[0].color = red
+newCar[0].color = red
+The new color of my Honda is purple
+myCar[0].color = purple
+newCar[0].color = purple
+
+ +

類陣例(Array-like)物件

+ +

slice method can also be called to convert Array-like objects / collections to a new Array. You just bind the method to the object. The {{jsxref("Functions/arguments", "arguments")}} inside a function is an example of an 'array-like object'.

+ +
function list() {
+  return Array.prototype.slice.call(arguments);
+}
+
+var list1 = list(1, 2, 3); // [1, 2, 3]
+
+ +

Binding can be done with the .call function of {{jsxref("Function.prototype")}} and it can also be reduced using [].slice.call(arguments) instead of Array.prototype.slice.call. Anyway, it can be simplified using {{jsxref("Function.prototype.bind", "bind")}}.

+ +
var unboundSlice = Array.prototype.slice;
+var slice = Function.prototype.call.bind(unboundSlice);
+
+function list() {
+  return slice(arguments);
+}
+
+var list1 = list(1, 2, 3); // [1, 2, 3]
+
+ +

Streamlining cross-browser behavior

+ +

Although host objects (such as DOM objects) are not required by spec to follow the Mozilla behavior when converted by Array.prototype.slice and IE < 9 does not do so, versions of IE starting with version 9 do allow this. “Shimming” it can allow reliable cross-browser behavior. As long as other modern browsers continue to support this ability, as currently do IE, Mozilla, Chrome, Safari, and Opera, developers reading (DOM-supporting) slice code relying on this shim will not be misled by the semantics; they can safely rely on the semantics to provide the now apparently de facto standard behavior. (The shim also fixes IE to work with the second argument of slice() being an explicit {{jsxref("null")}}/{{jsxref("undefined")}} value as earlier versions of IE also did not allow but all modern browsers, including IE >= 9, now do.)

+ +
/**
+ * Shim for "fixing" IE's lack of support (IE < 9) for applying slice
+ * on host objects like NamedNodeMap, NodeList, and HTMLCollection
+ * (technically, since host objects have been implementation-dependent,
+ * at least before ES2015, IE hasn't needed to work this way).
+ * Also works on strings, fixes IE < 9 to allow an explicit undefined
+ * for the 2nd argument (as in Firefox), and prevents errors when
+ * called on other DOM objects.
+ */
+(function () {
+  'use strict';
+  var _slice = Array.prototype.slice;
+
+  try {
+    // Can't be used with DOM elements in IE < 9
+    _slice.call(document.documentElement);
+  } catch (e) { // Fails in IE < 9
+    // This will work for genuine arrays, array-like objects,
+    // NamedNodeMap (attributes, entities, notations),
+    // NodeList (e.g., getElementsByTagName), HTMLCollection (e.g., childNodes),
+    // and will not fail on other DOM objects (as do DOM elements in IE < 9)
+    Array.prototype.slice = function(begin, end) {
+      // IE < 9 gets unhappy with an undefined end argument
+      end = (typeof end !== 'undefined') ? end : this.length;
+
+      // For native Array objects, we use the native slice function
+      if (Object.prototype.toString.call(this) === '[object Array]'){
+        return _slice.call(this, begin, end);
+      }
+
+      // For array like object we handle it ourselves.
+      var i, cloned = [],
+        size, len = this.length;
+
+      // Handle negative value for "begin"
+      var start = begin || 0;
+      start = (start >= 0) ? start : Math.max(0, len + start);
+
+      // Handle negative value for "end"
+      var upTo = (typeof end == 'number') ? Math.min(end, len) : len;
+      if (end < 0) {
+        upTo = len + end;
+      }
+
+      // Actual expected size of the slice
+      size = upTo - start;
+
+      if (size > 0) {
+        cloned = new Array(size);
+        if (this.charAt) {
+          for (i = 0; i < size; i++) {
+            cloned[i] = this.charAt(start + i);
+          }
+        } else {
+          for (i = 0; i < size; i++) {
+            cloned[i] = this[start + i];
+          }
+        }
+      }
+
+      return cloned;
+    };
+  }
+}());
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.10', 'Array.prototype.slice')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.slice', 'Array.prototype.slice')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.slice', 'Array.prototype.slice')}}{{Spec2('ESDraft')}}
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.slice")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/some/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/some/index.html new file mode 100644 index 0000000000..7dd0fbdf34 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/some/index.html @@ -0,0 +1,217 @@ +--- +title: Array.prototype.some() +slug: Web/JavaScript/Reference/Global_Objects/Array/some +tags: + - Array + - ECMAScript5 + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/some +--- +
{{JSRef}}
+ +

some() 方法會透過給定函式、測試陣列中是否至少有一個元素,通過該函式所實作的測試。這方法回傳的是布林值。

+ +
{{EmbedInteractiveExample("pages/js/array-some.html")}}
+ +
+

注意:如果輸入空陣列的話,這個方法會回傳 false

+
+ + + +

語法

+ +
arr.some(callback[, thisArg])
+ +

參數

+ +
+
callback
+
用來測試每一個元素的函式,它包含三個引數: +
+
currentValue
+
目前正要被處理的陣列元素。
+
index{{Optional_inline}}
+
目前正要被處理的陣列元素之索引值。
+
array{{Optional_inline}}
+
呼叫 some() 的陣列。
+
+
+
thisArg{{Optional_inline}}
+
執行 callback 回呼函式的 this 值。
+
+ +

回傳值

+ +

若回呼函式在處理任何一個陣列元素時得到 {{Glossary("truthy")}} 值,則回傳 true。否則,回傳值為 false

+ +

描述

+ +

The some() method executes the callback function once for each element present in the array until it finds the one where callback returns a truthy value (a value that becomes true when converted to a Boolean). If such an element is found, some() immediately returns true. Otherwise, some() returns false. callback is invoked only for indexes of the array with assigned values. It is not invoked for indexes which have been deleted or which have never been assigned values.

+ +

callback is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.

+ +

If a thisArg parameter is provided to some(), it will be used as the callback's this value. Otherwise, the value {{jsxref("undefined")}} will be used as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.

+ +

some() does not mutate the array on which it is called.

+ +

The range of elements processed by some() is set before the first invocation of callback. Elements appended to the array after the call to some() begins will not be visited by callback. If an existing, unvisited element of the array is changed by callback, its value passed to the visiting callback will be the value at the time that some() visits that element's index. Elements that are deleted are not visited.

+ +

範例

+ +

測試陣列元素的數值

+ +

以下範例將測試是否最少有一個元素的數值大於 10。

+ +
function isBiggerThan10(element, index, array) {
+  return element > 10;
+}
+
+[2, 5, 8, 1, 4].some(isBiggerThan10);  // false
+[12, 5, 8, 1, 4].some(isBiggerThan10); // true
+ +

{{ EmbedLiveSample('Testing_value_of_array_elements', '', '', '', 'Web/JavaScript/Reference/Global_Objects/Array/some') }}

+ +

使用箭頭函式測試

+ +

箭頭函式能給相同的測試,提供更簡潔的語法。

+ +
[2, 5, 8, 1, 4].some(x => x > 10); //false
+[12, 5, 8, 1, 4].some(x => x > 10); // true
+ +

{{ EmbedLiveSample('Testing_array_elements_using_arrow_functions', '', '', '', 'Web/JavaScript/Reference/Global_Objects/Array/some') }}

+ +

測試陣列元素的數值是否存在

+ +

To mimic the function of the includes() method, this custom function returns true if the element exists in the array:

+ +
const fruits = ['apple', 'banana', 'mango', 'guava'];
+
+function checkAvailability(arr, val) {
+  return arr.some(function(arrVal) {
+    return val === arrVal;
+  });
+}
+
+checkAvailability(fruits, 'kela');   // false
+checkAvailability(fruits, 'banana'); // true
+ +

{{ EmbedLiveSample('Checking_whether_a_value_exists_in_an_array', '', '', '', 'Web/JavaScript/Reference/Global_Objects/Array/some') }}

+ +

Checking whether a value exists using an arrow function

+ +
const fruits = ['apple', 'banana', 'mango', 'guava'];
+
+function checkAvailability(arr, val) {
+  return arr.some(arrVal => val === arrVal);
+}
+
+checkAvailability(fruits, 'kela');   // false
+checkAvailability(fruits, 'banana'); // true
+ +

{{ EmbedLiveSample('Checking_whether_a_value_exists_using_an_arrow_function', '', '', '', 'Experiment:StaticExamplesOnTop/JavaScript/Array/some') }}

+ +

Converting any value to Boolean

+ +
const TRUTHY_VALUES = [true, 'true', 1];
+
+function getBoolean(value) {
+  'use strict';
+
+  if (typeof value === 'string') {
+    value = value.toLowerCase().trim();
+  }
+
+  return TRUTHY_VALUES.some(function(t) {
+    return t === value;
+  });
+}
+
+getBoolean(false);   // false
+getBoolean('false'); // false
+getBoolean(1);       // true
+getBoolean('true');  // true
+ +

{{ EmbedLiveSample('Converting_any_value_to_Boolean', '', '', '', 'Web/JavaScript/Reference/Global_Objects/Array/some') }}

+ +

Polyfill

+ +

some() was added to the ECMA-262 standard in the 5th edition, and it may not be present in all implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of some() in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming {{jsxref("Object")}} and {{jsxref("TypeError")}} have their original values and that fun.call evaluates to the original value of {{jsxref("Function.prototype.call()")}}.

+ +
// Production steps of ECMA-262, Edition 5, 15.4.4.17
+// Reference: http://es5.github.io/#x15.4.4.17
+if (!Array.prototype.some) {
+  Array.prototype.some = function(fun, thisArg) {
+    'use strict';
+
+    if (this == null) {
+      throw new TypeError('Array.prototype.some called on null or undefined');
+    }
+
+    if (typeof fun !== 'function') {
+      throw new TypeError();
+    }
+
+    var t = Object(this);
+    var len = t.length >>> 0;
+
+    for (var i = 0; i < len; i++) {
+      if (i in t && fun.call(thisArg, t[i], i, t)) {
+        return true;
+      }
+    }
+
+    return false;
+  };
+}
+
+ +

{{ EmbedLiveSample('Polyfill', '', '', '', 'Web/JavaScript/Reference/Global_Objects/Array/some') }}

+ + +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態註解
{{SpecName('ES5.1', '#sec-15.4.4.17', 'Array.prototype.some')}}{{Spec2('ES5.1')}}初始定義。在 JavaScript 1.6 實作。
{{SpecName('ES6', '#sec-array.prototype.some', 'Array.prototype.some')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.some', 'Array.prototype.some')}}{{Spec2('ESDraft')}}
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.some")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/sort/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/sort/index.html new file mode 100644 index 0000000000..7240184a75 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/sort/index.html @@ -0,0 +1,248 @@ +--- +title: Array.prototype.sort() +slug: Web/JavaScript/Reference/Global_Objects/Array/sort +tags: + - Array + - JavaScript + - Method + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Array/sort +--- +
{{JSRef}}
+ +

sort() 方法會原地(in place)對一個陣列的所有元素進行排序,並回傳此陣列。排序不一定是穩定的(stable)。預設的排序順序是根據字串的 Unicode 編碼位置(code points)而定。

+ +

由於依賴執行環境的實作,所以並不能保證排序的時間及空間複雜度。

+ +
{{EmbedInteractiveExample("pages/js/array-sort.html")}}
+ + + +

語法

+ +
arr.sort([compareFunction])
+
+ +

參數

+ +
+
compareFunction {{optional_inline}}
+
指定一個函式來定義排序順序。假如省略此參數,陣列將根據各個元素轉為字串後的每一個字元之 Unicode 編碼位置值進行排序。
+
+ +

回傳值

+ +

排序後的陣列。請注意此為原地(in place)進行排序過的陣列,並且不是原陣列的拷貝。

+ +

描述

+ +

如果 compareFunction 沒有被應用,元素將被轉換為字串並以 Unicode 編碼位置進行比較來排序。舉例來說,"Banana" 會被排在 "cherry" 之前。在數值排序中,9 排在 80 前面,但因為數字被轉換成字串,在 Unicode 順序中 "80" 會在 "9" 的前面。

+ +

如果 compareFunction 被應用,陣列元素們將根據比較函式之回傳值來排序。如果 ab 為被比較之兩元素,則:

+ + + +

所以,比較函式會是以下形式:

+ +
function compare(a, b) {
+  if (在某排序標準下 a 小於 b) {
+    return -1;
+  }
+  if (在某排序標準下 a 大於 b) {
+    return 1;
+  }
+  // a 必須等於 b
+  return 0;
+}
+
+ +

為了比較數字而不是字串,比較函式可以僅僅利用 ab。以下函式將會升冪排序陣列:

+ +
function compareNumbers(a, b) {
+  return a - b;
+}
+
+ +

sort 方法可以直接使用{{jsxref("Operators/function", "函式運算式", "", 1)}}(以及閉包(closures)):

+ +
var numbers = [4, 2, 5, 1, 3];
+numbers.sort(function(a, b) {
+  return a - b;
+});
+console.log(numbers);
+
+// [1, 2, 3, 4, 5]
+
+ +

物件可以按照其中一個屬性的值來排序。

+ +
var items = [
+  { name: 'Edward', value: 21 },
+  { name: 'Sharpe', value: 37 },
+  { name: 'And', value: 45 },
+  { name: 'The', value: -12 },
+  { name: 'Magnetic', value: 13 },
+  { name: 'Zeros', value: 37 }
+];
+
+// sort by value
+items.sort(function (a, b) {
+  return a.value - b.value;
+});
+
+// sort by name
+items.sort(function(a, b) {
+  var nameA = a.name.toUpperCase(); // ignore upper and lowercase
+  var nameB = b.name.toUpperCase(); // ignore upper and lowercase
+  if (nameA < nameB) {
+    return -1;
+  }
+  if (nameA > nameB) {
+    return 1;
+  }
+
+  // names must be equal
+  return 0;
+});
+ +

範例

+ +

建立、顯示及排序一個陣列

+ +

下列範例建立了四個陣列並顯示其原本陣列內容、再進行排序。數字陣列先不使用比較函式(compare function)來排序,接著才依據比較函式進行排序。

+ +
var stringArray = ['Blue', 'Humpback', 'Beluga'];
+var numericStringArray = ['80', '9', '700'];
+var numberArray = [40, 1, 5, 200];
+var mixedNumericArray = ['80', '9', '700', 40, 1, 5, 200];
+
+function compareNumbers(a, b) {
+  return a - b;
+}
+
+console.log('stringArray:', stringArray.join());
+console.log('Sorted:', stringArray.sort());
+
+console.log('numberArray:', numberArray.join());
+console.log('Sorted without a compare function:', numberArray.sort());
+console.log('Sorted with compareNumbers:', numberArray.sort(compareNumbers));
+
+console.log('numericStringArray:', numericStringArray.join());
+console.log('Sorted without a compare function:', numericStringArray.sort());
+console.log('Sorted with compareNumbers:', numericStringArray.sort(compareNumbers));
+
+console.log('mixedNumericArray:', mixedNumericArray.join());
+console.log('Sorted without a compare function:', mixedNumericArray.sort());
+console.log('Sorted with compareNumbers:', mixedNumericArray.sort(compareNumbers));
+
+ +

這個範例將產生下列結果。就如結果所示,當使用比較函式時,數字會被正確的排序,不管是數字還是數字字串。

+ +
stringArray: Blue,Humpback,Beluga
+Sorted: Beluga,Blue,Humpback
+
+numberArray: 40,1,5,200
+Sorted without a compare function: 1,200,40,5
+Sorted with compareNumbers: 1,5,40,200
+
+numericStringArray: 80,9,700
+Sorted without a compare function: 700,80,9
+Sorted with compareNumbers: 9,80,700
+
+mixedNumericArray: 80,9,700,40,1,5,200
+Sorted without a compare function: 1,200,40,5,700,80,9
+Sorted with compareNumbers: 1,5,9,40,80,200,700
+
+ +

排序非 ASCII 字元

+ +

為了排列非 ASCII 字元,即重音節字元(e、é、è、a、ä 等等),非英語字串:利用 {{jsxref("String.localeCompare")}}。此函式將比較這些字元,所以結果將會顯示正確的順序。

+ +
var items = ['réservé', 'premier', 'cliché', 'communiqué', 'café', 'adieu'];
+items.sort(function (a, b) {
+  return a.localeCompare(b);
+});
+
+// items is ['adieu', 'café', 'cliché', 'communiqué', 'premier', 'réservé']
+
+ +

排序 map

+ +

compareFunction 可以被陣列中的各個元素多次呼叫。依據 compareFunction 的特性,這將會產生大量運算。越多元素要排序 compareFunction 就越多工作要做,因此選擇使用 map 來排列也就是一個更明智的選擇。作法為先迭代陣列一次來取得排序時所需的值至暫時的陣列,並對此臨時陣列進行排序。然後再迭代臨時陣列來將正確順序之值放入原始陣列中。

+ +
// the array to be sorted
+var list = ['Delta', 'alpha', 'CHARLIE', 'bravo'];
+
+// temporary array holds objects with position and sort-value
+var mapped = list.map(function(el, i) {
+  return { index: i, value: el.toLowerCase() };
+})
+
+// sorting the mapped array containing the reduced values
+mapped.sort(function(a, b) {
+  if (a.value > b.value) {
+    return 1;
+  }
+  if (a.value < b.value) {
+    return -1;
+  }
+  return 0;
+});
+
+// container for the resulting order
+var result = mapped.map(function(el){
+  return list[el.index];
+});
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
規格狀態註解
{{SpecName('ES1')}}{{Spec2('ES1')}}初始定義。
{{SpecName('ES5.1', '#sec-15.4.4.11', 'Array.prototype.sort')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.sort', 'Array.prototype.sort')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.sort', 'Array.prototype.sort')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.sort")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/splice/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/splice/index.html new file mode 100644 index 0000000000..2cb76617b8 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/splice/index.html @@ -0,0 +1,150 @@ +--- +title: Array.prototype.splice() +slug: Web/JavaScript/Reference/Global_Objects/Array/splice +tags: + - Array + - JavaScript + - Method + - Prototype + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Array/splice +--- +
{{JSRef}}
+ +

splice() 方法可以藉由刪除既有元素並/或加入新元素來改變一個陣列的內容。

+ +
{{EmbedInteractiveExample("pages/js/array-splice.html")}}
+ +

語法

+ +
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
+
+ +

參數

+ +
+
start
+
陣列中要開始改動的元素索引(起始為 0)。若索引大於陣列長度,則實際開始的索引值會被設為陣列長度。若索引為負,則會從陣列中最後一個元素開始往前改動(起始為 -1)且若其絕對值大於陣列的長度,則會被設為 0。
+
deleteCount {{optional_inline}}
+
一個表示欲刪除的原陣列元素數量的整數。
+
若省略了 deleteCount,或假如其值大於 array.length - start(也就是 deleteCount 大於 start 算起的剩餘元素數量),則所有從 start 開始到陣列中最後一個元素都會被刪除。
+
deleteCount 為 0 或是負數,則不會有元素被刪除。 因此,你應該給定至少一個欲加入的新元素(見下方說明)。
+
item1, item2, ... {{optional_inline}}
+
start 開始,要加入到陣列的元素。 如果你沒有指定任何元素,則 splice() 只會依照 startdeleteCount 刪除陣列的元素。
+
+ +

回傳值

+ +

一個包含被刪除的元素陣列。如果只有一個元素被刪除,依舊是回傳包含一個元素的陣列。 倘若沒有元素被刪除,則會回傳空陣列。

+ +

說明

+ +

如果你插入的元素數量和刪除的數量不同,則回傳的陣列長度也會和原先的不同。

+ +

範例

+ +

從索引 2 的位置開始,刪除 0 個元素並插入「drum」

+ +
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
+var removed = myFish.splice(2, 0, 'drum');
+
+// myFish 為 ["angel", "clown", "drum", "mandarin", "sturgeon"]
+// removed 為 [], 沒有元素被刪除
+
+ +

從索引 3 的位置開始,刪除 1 個元素

+ +
var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon'];
+var removed = myFish.splice(3, 1);
+
+// removed 為 ["mandarin"]
+// myFish 為 ["angel", "clown", "drum", "sturgeon"]
+
+ +

從索引 2 的位置開始,刪除 1 個元素並插入「trumpet」

+ +
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」

+ +
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 個元素

+ +
var myFish = ['parrot', 'anemone', 'blue', 'trumpet', 'sturgeon'];
+var removed = myFish.splice(myFish.length - 3, 2);
+
+// myFish 為 ["parrot", "anemone", "sturgeon"]
+// removed 為 ["blue", "trumpet"]
+ +

從索引 -2 的位置開始,刪除 1 個元素

+ +
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
+var removed = myFish.splice(-2, 1);
+
+// myFish 為 ["angel", "clown", "sturgeon"]
+// removed 為 ["mandarin"]
+ +

從索引 2 的位置開始,刪除所有元素(含索引 2)

+ +
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
+var removed = myFish.splice(2);
+
+// myFish 為 ["angel", "clown"]
+// removed 為 ["mandarin", "sturgeon"]
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態備註
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.12', 'Array.prototype.splice')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.splice', 'Array.prototype.splice')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.splice', 'Array.prototype.splice')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.splice")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/unshift/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/unshift/index.html new file mode 100644 index 0000000000..7864ea6359 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/unshift/index.html @@ -0,0 +1,101 @@ +--- +title: Array.prototype.unshift() +slug: Web/JavaScript/Reference/Global_Objects/Array/unshift +tags: + - JavaScript + - Method + - Prototype + - Reference + - unshift + - 陣列 +translation_of: Web/JavaScript/Reference/Global_Objects/Array/unshift +--- +
{{JSRef}}
+ +

unshift() 方法會添加一個或多個元素至陣列的開頭,並且回傳陣列的新長度。

+ +
{{EmbedInteractiveExample("pages/js/array-unshift.html")}}
+ +

語法

+ +
arr.unshift(element1[, ...[, elementN]])
+ +

參數

+ +
+
elementN
+
欲添加至陣列開頭的元素。
+
+ +

回傳值

+ +

呼叫此方法之物件的新 {{jsxref("Array.length", "length")}} 屬性值。

+ +

描述

+ +

unshift 方法會將一或多個給定值插入至一個類陣列(array-like)物件的開頭。

+ +

unshift 被刻意設計為具通用性;此方法可以藉由 {{jsxref("Function.call", "called", "", 1)}} 或 {{jsxref("Function.apply", "applied", "", 1)}} 應用於類似陣列的物件上。若欲應用此方法的物件不包含代表一系列啟始為零之數字屬性序列長度的 length 屬性,可能是不具任何意義的行為。

+ +

範例

+ +
var arr = [1, 2];
+
+arr.unshift(0); // 執行後的結果是3,其代表處理後的陣列長度
+// arr is [0, 1, 2]
+
+arr.unshift(-2, -1); // = 5
+// arr is [-2, -1, 0, 1, 2]
+
+arr.unshift([-3]);
+// arr is [[-3], -2, -1, 0, 1, 2]
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.13', 'Array.prototype.unshift')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.unshift', 'Array.prototype.unshift')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.unshift")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/array/values/index.html b/files/zh-tw/web/javascript/reference/global_objects/array/values/index.html new file mode 100644 index 0000000000..6f464a3d29 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/array/values/index.html @@ -0,0 +1,77 @@ +--- +title: Array.prototype.values() +slug: Web/JavaScript/Reference/Global_Objects/Array/values +translation_of: Web/JavaScript/Reference/Global_Objects/Array/values +--- +
{{JSRef}}
+ +

values() 方法會回傳一個包含陣列中的每一個索引之對應值(values)的新 Array Iterator 物件。

+ +
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
+ +

語法

+ +
arr.values()
+ +

回傳值

+ +

一個新的 {{jsxref("Array")}} 迭代器(iterator)物件。

+ +

範例

+ +

使用 for...of 迴圈進行迭代

+ +
var arr = ['w', 'y', 'k', 'o', 'p'];
+var iterator = arr.values();
+
+for (let letter of iterator) {
+  console.log(letter);
+}
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-array.prototype.values', 'Array.prototype.values')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-array.prototype.values', 'Array.prototype.values')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Array.values")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/arraybuffer/index.html b/files/zh-tw/web/javascript/reference/global_objects/arraybuffer/index.html new file mode 100644 index 0000000000..1fa59e5f0f --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/arraybuffer/index.html @@ -0,0 +1,225 @@ +--- +title: ArrayBuffer +slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer +translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer +--- +

{{JSRef}}

+ +

ArrayBuffer 物件是一種表示通用、固定大小的原始二進制資料緩衝。想要直接操作一個 ArrayBuffer 物件的內容是不可能的。若要讀寫該緩衝的內容則必須透過視圖,可以選擇建立一個 {{jsxref("DataView")}} 視圖物件或是一個限定其成員為某種型別的 {{jsxref("TypedArray")}} 視圖物件,它們皆能以特定的型別解讀、修改 ArrayBuffer

+ +

語法

+ +
new ArrayBuffer(length)
+
+ +

參數

+ +
+
length
+
要建立的緩衝陣列大小,以位元組(byte)計算。
+
+ +

回傳值

+ +

為一個新建立的指定大小 ArrayBuffer 物件,其內容皆初始化為 0。

+ +

Exceptions

+ +

A {{jsxref("RangeError")}} is thrown if the length is larger than {{jsxref("Number.MAX_SAFE_INTEGER")}} (>= 2 ** 53) or negative.

+ +

說明

+ +

The ArrayBuffer constructor creates a new ArrayBuffer of the given length in bytes.

+ +

從既有的資料取得 ArrayBuffer

+ + + +

屬性

+ +
+
ArrayBuffer.length
+
The ArrayBuffer constructor's length property whose value is 1.
+
{{jsxref("ArrayBuffer.@@species", "get ArrayBuffer[@@species]")}}
+
The constructor function that is used to create derived objects.
+
{{jsxref("ArrayBuffer.prototype")}}
+
Allows the addition of properties to all ArrayBuffer objects.
+
+ +

方法

+ +
+
{{jsxref("ArrayBuffer.isView", "ArrayBuffer.isView(arg)")}}
+
Returns true if arg is one of the ArrayBuffer views, such as typed array objects or a {{jsxref("DataView")}}. Returns false otherwise.
+
{{jsxref("ArrayBuffer.transfer", "ArrayBuffer.transfer(oldBuffer [, newByteLength])")}} {{experimental_inline}}
+
+
Returns a new ArrayBuffer whose contents are taken from the oldBuffer's data and then is either truncated or zero-extended by newByteLength.
+
+
+ +

ArrayBuffer 實例

+ +

所有的 ArrayBuffer 物件實例皆繼承自 {{jsxref("ArrayBuffer.prototype")}}.

+ +

屬性

+ +

{{page('zh-TW/Web/JavaScript/JavaScript_typed_arrays/ArrayBuffer/prototype','屬性')}}

+ +

方法

+ +

{{page('/zh-TW/docs/Web/JavaScript/JavaScript_typed_arrays/ArrayBuffer/prototype','方法')}}

+ +
+
{{jsxref("ArrayBuffer.slice()")}} {{non-standard_inline}}
+
Has the same functionality as {{jsxref("ArrayBuffer.prototype.slice()")}}.
+
+ +

範例

+ +

In this example, we create a 8-byte buffer with a {{jsxref("Global_Objects/Int32Array", "Int32Array")}} view referring to the buffer:

+ +
var buffer = new ArrayBuffer(8);
+var view   = new Int32Array(buffer);
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Typed Array')}}{{Spec2('Typed Array')}}Superseded by ECMAScript 6.
{{SpecName('ES6', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}{{Spec2('ES6')}}Initial definition in an ECMA standard. Specified that new is required.
{{SpecName('ESDraft', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support7.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("2")}}1011.65.1
ArrayBuffer() without new throws{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("44")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ArrayBuffer.slice() {{non-standard_inline}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+ {{CompatNo}} {{CompatGeckoDesktop("53")}}
{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support4.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("2")}}1011.64.2
ArrayBuffer() without new throws{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("44")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ArrayBuffer.slice() {{non-standard_inline}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+ {{CompatNo}} {{CompatGeckoMobile("53")}}
{{CompatNo}}{{CompatNo}}{{CompatUnknown}}
+
+ +

相容性備註

+ +

Starting with ECMAScript 2015, ArrayBuffer constructors require to be constructed with a {{jsxref("Operators/new", "new")}} operator. Calling an ArrayBuffer constructor as a function without new, will throw a {{jsxref("TypeError")}} from now on.

+ +
var dv = ArrayBuffer(10);
+// TypeError: calling a builtin ArrayBuffer constructor
+// without new is forbidden
+ +
var dv = new ArrayBuffer(10);
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/arraybuffer/prototype/index.html b/files/zh-tw/web/javascript/reference/global_objects/arraybuffer/prototype/index.html new file mode 100644 index 0000000000..8883a89cec --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/arraybuffer/prototype/index.html @@ -0,0 +1,110 @@ +--- +title: ArrayBuffer.prototype +slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer +--- +
{{JSRef}}
+ +

The ArrayBuffer.prototype property represents the prototype for the {{jsxref("ArrayBuffer")}} object.

+ +
{{js_property_attributes(0,0,0)}}
+ +

描述

+ +

ArrayBuffer instances inherit from ArrayBuffer.prototype. As with all constructors, you can change the constructor's prototype object to make changes to all ArrayBuffer instances.

+ +

屬性

+ +
+
ArrayBuffer.prototype.constructor
+
Specifies the function that creates an object's prototype. The initial value is the standard built-in ArrayBuffer constructor.
+
{{jsxref("ArrayBuffer.prototype.byteLength")}} {{readonlyInline}}
+
陣列大小,以位元組(byte)計算。此屬性在陣列建立之後就不可能改變了。唯讀
+
+ +

方法

+ +
+
{{jsxref("ArrayBuffer.prototype.slice()")}}
+
Returns a new ArrayBuffer whose contents are a copy of this ArrayBuffer's bytes from begin, inclusive, up to end, exclusive. If either begin or end is negative, it refers to an index from the end of the array, as opposed to from the beginning.
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-arraybuffer.prototype', 'ArrayBuffer.prototype')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-arraybuffer.prototype', 'ArrayBuffer.prototype')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support7.0{{ CompatGeckoDesktop("2")}}1011.65.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support4.0{{CompatVersionUnknown}}{{CompatGeckoMobile("2")}}1011.64.2
+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/asyncfunction/index.html b/files/zh-tw/web/javascript/reference/global_objects/asyncfunction/index.html new file mode 100644 index 0000000000..c25f3ee3a1 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/asyncfunction/index.html @@ -0,0 +1,118 @@ +--- +title: AsyncFunction +slug: Web/JavaScript/Reference/Global_Objects/AsyncFunction +translation_of: Web/JavaScript/Reference/Global_Objects/AsyncFunction +--- +
{{JSRef}}
+ +

AsyncFunction 建構子建立一個新的 {{jsxref("Statements/async_function", "async function")}}  物件。在 JavaScript 中,每一個非同步函數實際上是一個 AsyncFunction 物件。

+ +

注意 AsyncFunction 不是一個全域物件。 它可以以下程式碼獲得。

+ +
Object.getPrototypeOf(async function(){}).constructor
+
+ +

語法

+ +
new AsyncFunction([arg1[, arg2[, ...argN]],] functionBody)
+ +

參數

+ +
+
arg1, arg2, ... argN
+
Names to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b".
+
functionBody
+
一個字串。描述該函數定義的陳述式(statements)。
+
+ +

說明

+ +

{{jsxref("Statements/async_function", "async function")}} objects created with the AsyncFunction constructor are parsed when the function is created. This is less efficient than declaring an async function with an {{jsxref("Statements/async_function", "async function expression")}} and calling it within your code, because such functions are parsed with the rest of the code.

+ +

All arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed.

+ +
+

Note: {{jsxref("Statements/async_function", "async functions")}} created with the AsyncFunction constructor do not create closures to their creation contexts; they are always created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the AsyncFunction constructor was called. This is different from using {{jsxref("Global_Objects/eval", "eval")}} with code for an async function expression.

+
+ +

以函數的方式執行 AsyncFunction 建構式 (不使用 new 運算子) 和以建構子的方式執行是等效的。

+ +

屬性

+ +
+
AsyncFunction.length
+
AsyncFuction 建構子的長度為 1。
+
{{jsxref("AsyncFunction.prototype")}}
+
可加入屬性至所有陣列物件。
+
+ +

AsyncFunction 原型物件

+ +

屬性

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/AsyncFunction/prototype', 'Properties')}}
+ +

AsyncFunction 實例

+ +

AsyncFunction 實例繼承 {{jsxref("AsyncFunction.prototype")}} 的屬性和方法. 和所有的建構子一樣,變更該建構子 (constructor) 的原型物件 (prototype object)將會影響所有的 AsyncFunction 實例。

+ +

範例

+ +

 AsyncFunction 建構子建立一個非同步函數

+ +
function resolveAfter2Seconds(x) {
+  return new Promise(resolve => {
+    setTimeout(() => {
+      resolve(x);
+    }, 2000);
+  });
+}
+
+var AsyncFunction = Object.getPrototypeOf(async function(){}).constructor
+
+var a = new AsyncFunction('a',
+                          'b',
+                          'return await resolveAfter2Seconds(a) + await resolveAfter2Seconds(b);');
+
+a(10, 20).then(v => {
+  console.log(v); // prints 30 after 4 seconds
+});
+
+ +

規範

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-async-function-objects', 'AsyncFunction object')}}{{Spec2('ESDraft')}}Initial definition in ES2017.
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.AsyncFunction")}}

+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/bigint/index.html b/files/zh-tw/web/javascript/reference/global_objects/bigint/index.html new file mode 100644 index 0000000000..705a85e255 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/bigint/index.html @@ -0,0 +1,279 @@ +--- +title: BigInt +slug: Web/JavaScript/Reference/Global_Objects/BigInt +translation_of: Web/JavaScript/Reference/Global_Objects/BigInt +--- +

{{JSRef}}{{SeeCompatTable}}

+ +

BigInt 是一個內建的物件,提供了表示大於253的整數的功能 (253是JavaScript原生的{{JSxRef("Number")}}能夠表示的最大值)

+ +

語法

+ +
BigInt(value);
+
+ +

參數

+ +
+
value
+
欲創建的數值,可以為整數或字串。
+
+ +
+

Note: BigInt() 不和 {{JSxRef("Operators/new", "new")}} 一起使用。

+
+ +
+
+ +

說明

+ +

BigInt 是透過在一個數值後加上 n ,例如 10n ,或呼叫 BigInt() 所生成的。

+ +
const theBiggestInt = 9007199254740991n;
+
+const alsoHuge = BigInt(9007199254740991);
+// ↪ 9007199254740991n
+
+const hugeString = BigInt("9007199254740991");
+// ↪ 9007199254740991n
+
+const hugeHex = BigInt("0x1fffffffffffff");
+// ↪ 9007199254740991n
+
+const hugeBin = BigInt("0b11111111111111111111111111111111111111111111111111111");
+// ↪ 9007199254740991n
+
+ +

BigInt 跟 {{JSxRef("Number")}} 很像,但在某些部分有些許不同 — 它不可以被用在內建的 {{JSxRef("Math")}} 物件方法中、而且不可以跟 Number 的實體混用運算子。

+ +
+

{{JSxRef("Number")}} 和 BigInt 不能混和計算 — 他們必須被轉換到同一個型態。

+ +

然而,在相互轉換時要注意, BigInt 在被轉換成 Number 時可能會遺失部分精度的資訊。

+
+ +

類別資訊

+ +

當使用 typeof 測試時,一個 BigInt 會回傳 "bigint":

+ +
typeof 1n === 'bigint'; // true
+typeof BigInt('1') === 'bigint'; // true
+
+ +

當使用 Object 來包裹時,BigInt 會被看成是普通的 "object" 型態:

+ +
typeof Object(1n) === 'object'; // true
+
+ +

Operators

+ +

下列的運算子可以被用在 BigInt 上 (或由object包裹的 BigInt): +, *, -, **, %.

+ +
const previousMaxSafe = BigInt(Number.MAX_SAFE_INTEGER);
+// ↪ 9007199254740991
+
+const maxPlusOne = previousMaxSafe + 1n;
+// ↪ 9007199254740992n
+
+const theFuture = previousMaxSafe + 2n;
+// ↪ 9007199254740993n, this works now!
+
+const multi = previousMaxSafe * 2n;
+// ↪ 18014398509481982n
+
+const subtr = multi – 10n;
+// ↪ 18014398509481972n
+
+const mod = multi % 10n;
+// ↪ 2n
+
+const bigN = 2n ** 54n;
+// ↪ 18014398509481984n
+
+bigN * -1n
+// ↪ –18014398509481984n
+
+ +

/ 運算子也同樣的能夠運行。然而,因為型態是 BigInt 而不是 BigDecimal ,除法運算會無條件捨去小數。也就是說,回傳值不會包含小數部分。

+ +
+

回傳值帶小數的運算在使用BigInt  時小數部分會被捨去。

+
+ +
const expected = 4n / 2n;
+// ↪ 2n
+
+const rounded = 5n / 2n;
+// ↪ 2n, not 2.5n
+
+
+ +

比較

+ +

一個 BigInt 並不嚴格等於一個 {{JSxRef("Global_Objects/Number", "Number")}},但他們會一般相等。

+ +
0n === 0
+// ↪ false
+
+0n == 0
+// ↪ true
+ +

一個 {{JSxRef("Global_Objects/Number", "Number")}} 和 BigInt 可以像普通運算一樣比較。

+ +
1n < 2
+// ↪ true
+
+2n > 1
+// ↪ true
+
+2 > 2
+// ↪ false
+
+2n > 2
+// ↪ false
+
+2n >= 2
+// ↪ true
+ +

他們可以參雜在陣列中並照預期的被排序。

+ +
const mixed = [4n, 6, -12n, 10, 4, 0, 0n];
+// ↪  [4n, 6, -12n, 10, 4, 0, 0n]
+
+mixed.sort();
+// ↪ [-12n, 0, 0n, 10, 4n, 4, 6]
+
+ +

Note that comparisons with Object-wrapped BigInts act as with other objects, only indicating equality when the same object instance is compared:

+ +
0n === Object(0n); // false
+Object(0n) === Object(0n); // false
+
+const o = Object(0n);
+o === o // true
+
+ +

Conditionals

+ +

A BigInt behaves like a {{JSxRef("Global_Objects/Number", "Number")}} in cases where it is converted to a {{JSxRef("Global_Objects/Boolean", "Boolean")}}: via the {{JSxRef("Global_Objects/Boolean", "Boolean")}} function; when used with logical operators {{JSxRef("Operators/Logical_Operators", "Logical Operators")}} ||, &&, and !; or within a conditional test like an {{JSxRef("Statements/if...else", "if statement")}}.

+ +
if (0n) {
+  console.log('Hello from the if!');
+} else {
+  console.log('Hello from the else!');
+}
+
+// ↪ "Hello from the else!"
+
+0n || 12n
+// ↪ 12n
+
+0n && 12n
+// ↪ 0n
+
+Boolean(0n)
+// ↪ false
+
+Boolean(12n)
+// ↪ true
+
+!12n
+// ↪ false
+
+!0n
+// ↪ true
+
+ +

方法

+ +
+
{{JSxRef("BigInt.asIntN()")}}
+
Wraps a BigInt between -2width-1 and 2width-1-1
+
{{JSxRef("BigInt.asUintN()")}}
+
Wraps a BigInt between 0 and 2width-1
+
+ +

屬性

+ +
+
{{JSxRef("BigInt.prototype")}}
+
允許對一個 BigInt 物件增加其屬性。
+
+ +

BigInt 物件實體

+ +

All BigInt instances inherit from BigInt.prototype. The prototype object of the BigInt constructor can be modified to affect all BigInt instances.

+ +

方法

+ +

{{page("/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt/prototype", "Methods")}}

+ +

建議用法

+ +

轉型

+ +

因為在 {{JSxRef("Global_Objects/Number", "Number")}} 和 BigInt 之間轉換可能造成精度遺失,建議當數值會超過253時只使用 BigInt ,而不要在兩者之間進行轉換。

+ +

加密

+ +

BigInt 支援的運算並非常數時間。因此 BigInt 不適用在加密學上

+ +

範例

+ +

計算質數

+ +
function isPrime(p) {
+  for (let i = 2n; i * i <= p; i++) {
+    if (p % i === 0n) return false;
+  }
+  return true;
+}
+
+// Takes a BigInt as an argument and returns a BigInt
+function nthPrime(nth) {
+  let maybePrime = 2n;
+  let prime = 0n;
+
+  while (nth >= 0n) {
+    if (isPrime(maybePrime)) {
+      nth -= 1n;
+      prime = maybePrime;
+    }
+    maybePrime += 1n;
+  }
+
+  return prime;
+}
+
+nthPrime(20n)
+// ↪ 73n
+ +

規範

+ + + + + + + + + + + + +
規範狀態
BigIntStage 3
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.BigInt")}}

+
+ +

另見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/boolean/index.html b/files/zh-tw/web/javascript/reference/global_objects/boolean/index.html new file mode 100644 index 0000000000..6c8d690b15 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/boolean/index.html @@ -0,0 +1,199 @@ +--- +title: Boolean +slug: Web/JavaScript/Reference/Global_Objects/Boolean +translation_of: Web/JavaScript/Reference/Global_Objects/Boolean +--- +
{{JSRef}}
+ +

Boolean 是布林值的包覆器。

+ +

語法

+ +
new Boolean([value])
+ +

參數

+ +
+
value {{optional_inline}}
+
這個Boolean物件的初始值。
+
+ +

說明

+ +

傳入的第一個參數值,如果需要的話,會被轉換成布林值。如果沒傳值,或者是0-0、{{jsxref("null")}}、false、{{jsxref("NaN")}}、{{jsxref("undefined")}}、空字串("")的話,這個物件的值會被初始化成false。大多數情況下,DOM 物件 {{domxref("document.all")}} 被傳入後,也會將其初始化為false。至於其他的值,包含所有物件或"false"字串,都會使其初始化為true

+ +

不要將原始型別的布林值和這個布林物件搞混,它們並不相同。

+ +

在判斷式中,任何物件只要不是 {{jsxref("undefined")}} 或 {{jsxref("null")}} ,儘管是值為false 的 Boolean 物件,都會被轉換成true。舉例來說,下列的 {{jsxref("Statements/if...else", "if")}} 判斷式中的布林值即為true

+ +
var x = new Boolean(false);
+if (x) {
+  // this code is executed
+}
+
+ +

以上這個行為和Boolean原始型別沒有關連,反倒是下面的 {{jsxref("Statements/if...else", "if")}} 判斷式會正確地將其視為false

+ +
var x = false;
+if (x) {
+  // this code is not executed
+}
+
+ +

不要用Boolean物件將非布林值轉換成布林值。反而要將Boolean視為函式去轉換非布林值:

+ +
var x = Boolean(expression);     // 較好
+var x = new Boolean(expression); // 不要用
+
+ +

如果你要指定任何物件,包括值為falseBoolean物件,作為Boolean物件的初始值,則該Boolean物件的值依舊為true

+ +
var myFalse = new Boolean(false);   // 初始值給false,實際上為true
+var g = new Boolean(myFalse);       // 想當然耳,true
+var myString = new String('Hello'); // 字串物件,'Hello'
+var s = new Boolean(myString);      // 依舊為true
+
+ +

不要使用Boolean物件代替Boolean的原始型別!

+ +

屬性

+ +
+
Boolean.length
+
長度永遠為1。
+
{{jsxref("Boolean.prototype")}}
+
原型為Boolean的建構式。
+
+ +

方法

+ +

全域的Boolean物件自身沒有任何方法,它只有從原型鏈繼承而來的方法。

+ +

Boolean 實體

+ +

所有 Boolean 實體會繼承 {{jsxref("Boolean.prototype")}} 。和所有建構式一樣,原型物件會指派給實體那些繼承的屬性和方法。

+ +

屬性

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean/prototype', 'Properties')}}
+ +

方法

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean/prototype', 'Methods')}}
+ +

範例

+ +

false 作為初始值建立 Boolean 物件

+ +
var bNoParam = new Boolean();
+var bZero = new Boolean(0);
+var bNull = new Boolean(null);
+var bEmptyString = new Boolean('');
+var bfalse = new Boolean(false);
+
+ +

true 作為初始值建立 Boolean 物件

+ +
var btrue = new Boolean(true);
+var btrueString = new Boolean('true');
+var bfalseString = new Boolean('false');
+var bSuLin = new Boolean('Su Lin');
+var bArrayProto = new Boolean([]);
+var bObjProto = new Boolean({});
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態註記
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.6', 'Boolean')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-boolean-objects', 'Boolean')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-boolean-objects', 'Boolean')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatIE("6.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/dataview/index.html b/files/zh-tw/web/javascript/reference/global_objects/dataview/index.html new file mode 100644 index 0000000000..d7cf6d6ed4 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/dataview/index.html @@ -0,0 +1,173 @@ +--- +title: DataView +slug: Web/JavaScript/Reference/Global_Objects/DataView +translation_of: Web/JavaScript/Reference/Global_Objects/DataView +--- +
{{JSRef}}
+ +

DataView 視圖提供了一個底層介面來讀寫 {{jsxref("ArrayBuffer")}} 中的二進位資料。DataView 能用多種不同的型別對 ArrayBuffer 進行修改、解讀,且可自訂資料的位元組順序而不受系統平台限制。DataView 物件僅為視圖,並不會存放資料,所有的資料皆實際儲存於 ArrayBuffer 物件當中。

+ +

語法

+ +
new DataView(buffer [, byteOffset [, byteLength]])
+ +

參數

+ +
+
buffer
+
要給DataView物件操作的資料容器並且不能為null
+
byteOffset {{optional_inline}}
+
The offset, in bytes, to the first byte in the specified buffer for the new view to reference. If not specified, the view of the buffer will start with the first byte.
+
byteLength {{optional_inline}}
+
The number of elements in the byte array. If unspecified, length of the view will match the buffer's length.
+
+ +

回傳值

+ +

A new DataView object representing the specified data buffer.

+ +

Errors thrown

+ +
+
{{jsxref("RangeError")}}
+
Thrown if the byteOffset and byteLength result in the specified view extending past the end of the buffer.
+
+ +

描述

+ +

位元組順序

+ +

Multi-byte number formats are represented in memory differently depending on machine architecture, see {{Glossary("Endianness")}} for an explanation. DataView accessors provide explicit control of how data will be accessed irrespective of the platform architecture's endianness.

+ +
var littleEndian = (function() {
+  var buffer = new ArrayBuffer(2);
+  new DataView(buffer).setInt16(0, 256, true /* littleEndian */);
+  // Int16Array uses the platform's endianness.
+  return new Int16Array(buffer)[0] === 256;
+})();
+console.log(littleEndian); // true or false
+
+ +

屬性

+ +
+
DataView.length
+
The DataView constructor's length property whose value is 3.
+
{{jsxref("DataView.prototype")}}
+
Allows the addition of properties to all DataView objects.
+
+ +

DataView 實例

+ +

All DataView instances inherit from {{jsxref("DataView.prototype")}}.

+ +

屬性

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/DataView/prototype','Properties')}}

+ +

方法

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/DataView/prototype','Methods')}}

+ +

範例

+ +
var buffer = new ArrayBuffer(16);
+var dv = new DataView(buffer, 0);
+
+dv.setInt16(1, 42);
+dv.getInt16(1); //42
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Typed Array')}}{{Spec2('Typed Array')}}Superseded by ECMAScript 6
{{SpecName('ES6', '#sec-dataview-constructor', 'DataView')}}{{Spec2('ES6')}}Initial definition in an ECMA standard
{{SpecName('ESDraft', '#sec-dataview-constructor', 'DataView')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support9.0{{CompatGeckoDesktop("15.0")}}1012.15.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support4.0{{CompatVersionUnknown}}{{CompatGeckoMobile("15")}}{{CompatUnknown}}12.04.2
+
+ +

Firefox-specific notes

+ +

Starting with Gecko / SpiderMonkey 40 {{geckoRelease(40)}}, DataView requires to be constructed with a {{jsxref("Operators/new", "new")}} operator. Calling DataView() as a function without new, will throw a {{jsxref("TypeError")}} from now on.

+ +
var dv = DataView(buffer, 0);
+// TypeError: calling a builtin DataView constructor without new is forbidden
+ +
var dv = new DataView(buffer, 0);
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/date/getday/index.html b/files/zh-tw/web/javascript/reference/global_objects/date/getday/index.html new file mode 100644 index 0000000000..abdc0e89a1 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/date/getday/index.html @@ -0,0 +1,72 @@ +--- +title: Date.prototype.getDay() +slug: Web/JavaScript/Reference/Global_Objects/Date/getDay +translation_of: Web/JavaScript/Reference/Global_Objects/Date/getDay +--- +
{{JSRef}}
+ +

getDay() 方法會根據當地時間將指定日期返回一星期中的第幾天,其中0代表星期日。 在當月的某天可以參考{{jsxref("Date.prototype.getDate()")}}。

+ +
{{EmbedInteractiveExample("pages/js/date-getday.html", "shorter")}}
+ + + +

語法

+ +
dateObj.getDay()
+ +

返回值

+ +

返回一個整數,數值介於0到6之間,取決於當地時間對應出指定日期為星期幾:0代表星期日,1代表星期一,2代表星期二,依此類推。

+ +

範例

+ +

使用 getDay()

+ +

下面第二行表示根據日期對象'Xmas95'的值,把1賦值給'weekday'。則1995年12月25日是星期一。

+ +
var Xmas95 = new Date('December 25, 1995 23:15:30');
+var weekday = Xmas95.getDay();
+
+console.log(weekday); // 1
+
+ +
+

Note: 如果需要,可以使用{{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}}加上options參數來獲取星期幾全名。使使用此方法能輕鬆做出各種國際語言:

+ +
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
{{SpecName('ESDraft', '#sec-date.prototype.getday', 'Date.prototype.getDay')}}
+ +

瀏覽器兼容性

+ + + +

{{Compat("javascript.builtins.Date.getDay")}}

+ +

See also

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/date/index.html b/files/zh-tw/web/javascript/reference/global_objects/date/index.html new file mode 100644 index 0000000000..91c0305aa4 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/date/index.html @@ -0,0 +1,263 @@ +--- +title: Date +slug: Web/JavaScript/Reference/Global_Objects/Date +tags: + - Date + - JavaScript +translation_of: Web/JavaScript/Reference/Global_Objects/Date +--- +
{{JSRef}}
+ +

建立一個  JavaScript Date 物件來指向某一個時間點。Date 物件是基於世界標準時間(UTC) 1970 年 1 月 1 日開始的毫秒數值來儲存時間。

+ +

語法

+ +
new Date();
+new Date(value);
+new Date(dateString);
+new Date(year, month[, day[, hour[, minutes[, seconds[, milliseconds]]]]]);
+
+ +
+

附註: JavaScript Date 物件只能由以 Date 作為建構子來產生,如果把 Date 作為一般的函數來呼叫(省略掉 {{jsxref("Operators/new", "new")}} 運算子)將會得到一個字串而非 Date 物件;與其它 JavaScript 物件不同,它並沒有物件實體語法(例如:以中刮號 [ ] 表示陣列的宣告方式)。

+
+ +

參數

+ +
+

附註:當傳入超過一個參數到 Date 建構子,若參數值超過它的合理範圍(例如:傳數值 13 到月份,或傳數值 70 給分鐘),相鄰的參數值將會被調整。例如: new Date(2013, 13, 1) 將等同於 new Date(2014, 1, 1) 都會建立代表 2014-02-01 的物件(注意月份值由 0 開始)。同樣的, new Date(2013, 2, 1, 0, 70)new Date(2013, 2, 1, 1, 10) 一樣會建立代表 2013-03-01T01:10:00 的 Date 物件。

+
+ +
+

附註:當傳入超過一個參數到 Date 建構子,所指定的參數值會視為本地時間。如果希望指定的值為世界標準時間(UTC),則應使用 new Date({{jsxref("Date.UTC()", "Date.UTC(...)")}}) 語法,傳入一樣格式的參數。

+
+ +
+
value
+
自世界標準時間(UTC) 1970 年 1 月 1 日 00:00:00 開始的毫秒整數(Integer)值(Unix 紀元;但要注意到大多 Unix 時間戳記是以秒而非毫秒為單位)。
+
dateString
+
表示時間日期的字串。這個字串應該要能被 {{jsxref("Date.parse()")}} 方法解析(符合 IETF-compliant RFC 2822 timestampsversion of ISO8601 格式要求). +
+

附註: 由於各家瀏覽器有所不同且具有差異性,因此非常不鼓勵使用 Date 建構子(或 Date.parse 方法,它們是同等的)來解析時間日期字串。

+
+
+
year
+
表示年份的整數。當數值落在 0 到 99 之間,表示 1900 到 1999 之間的年份。參考{{anch("Two_digit_years_map_to_1900_-_1999", "下面的範例")}}.
+
month
+
表示月份的整數。由 0 開始(一月)到 11 (十二月)。
+
day
+
選用。表示月份中第幾天的整數值。
+
hour
+
選用。表示小時數的整數值。
+
minute
+
選用。表示分鐘數的整數值。
+
second
+
選用。表示秒數的整數值。
+
millisecond
+
選用。表示毫秒數的整數值。
+
+ +

描述

+ + + +

屬性

+ +
+
{{jsxref("Date.prototype")}}
+
允許填加屬於到 JavaScript Date 物件。
+
Date.length
+
Date.length 的值為 7。這是建構子能夠處理的參數數量。
+
+ +

方法

+ +
+
{{jsxref("Date.now()")}}
+
回傳對應於當下時間的數值 - 1970/01/01 00:00:00 (UTC) 到當下的毫秒數。
+
{{jsxref("Date.parse()")}}
+
解析字串所表示的時間,回傳由 1970/01/01 00:00:00 (UTC) 到該時間的毫秒數值。 +
+

附註:由於瀏覽器之間的不同與差異,強烈不建議使用 Date.parse

+
+
+
{{jsxref("Date.UTC()")}}
+
需要傳入與建構子相同的參數數目(即 2 到 7 個),會得到由 1970-01-01 00:00:00 UTC 到該日期時間的毫秒數。(輸入的參數會視為世界標準時間,而非本地時間)
+
+ +

JavaScript Date 物件實體

+ +

所有 Date 物件實體繼承自 {{jsxref("Date.prototype")}} 。這個 Date 建構子的 prototype 物件可以被修改以影響所有 Date 物件實體。

+ +

Date.prototype 方法

+ +
{{page('/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Date/prototype', '方法')}}
+ +

範例

+ +

幾種建立 Date 物件的方式

+ +

接下來的幾個範例,展示幾種建立 Date 物件的方式:

+ +
+

附註: 由於瀏覽器之間的不同與差異,強烈不建議使用解析字串的方式建立 Date 物件。

+
+ +
var today = new Date();
+var birthday = new Date('December 17, 1995 03:24:00');
+var birthday = new Date('1995-12-17T03:24:00');
+var birthday = new Date(1995, 11, 17);
+var birthday = new Date(1995, 11, 17, 3, 24, 0);
+
+ +

兩位數的年份對應到 1900 - 1999

+ +

為了建立及取得西元 0 到 99 的日期,應該使用 {{jsxref("Date.prototype.setFullYear()")}} 以及 {{jsxref("Date.prototype.getFullYear()")}} 方法。

+ +
var date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
+
+// 過時的方法,98 在這裡對應到 1998 年
+date.setYear(98);           // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
+
+date.setFullYear(98);       // Sat Feb 01 0098 00:00:00 GMT+0000 (BST)
+
+ +

計算執行時間

+ +

下面的例子展示如何使用兩個 Date 物件來求得執行程式所花費毫秒數。

+ +

由於日(在夏令時轉換時)、月及年的長度並非固定,如果表示經過時間採用時、分、秒以外的單位,需要對這些差異作深入的研究,以處理可能發生的問題。

+ +
// 使用 Date 物件
+var start = Date.now();
+
+// 要計算執行時間的程式放在這裡
+doSomethingForALongTime();
+var end = Date.now();
+var elapsed = end - start; // 執行程式經過的毫秒數
+
+ +
// 使用內建方法
+var start = new Date();
+
+// 要計算執行時間的程式放在這裡
+doSomethingForALongTime();
+var end = new Date();
+var elapsed = end.getTime() - start.getTime(); // 執行程式經過的毫秒數
+
+ +
// 測試一個函數執行時間,並返回其回傳值
+function printElapsedTime(fTest) {
+  var nStartTime = Date.now(),
+      vReturn = fTest(),
+      nEndTime = Date.now();
+
+  console.log('Elapsed time: ' + String(nEndTime - nStartTime) + ' milliseconds');
+  return vReturn;
+}
+
+yourFunctionReturn = printElapsedTime(yourFunction);
+
+ +
+

附註:在瀏覽器支援 {{domxref("window.performance", "Web Performance API", "", 1)}} 高精度特性下, {{domxref("Performance.now()")}} 可以提供比 {{jsxref("Date.now()")}} 更可靠、精確的執行時間測試結果。

+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態
{{SpecName('ESDraft', '#sec-date-objects', 'Date')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-date-objects', 'Date')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.9', 'Date')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}}初步定義。實作在 JavaScript 1.1。
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
平台ChromeFirefox (Gecko)Internet ExplorerOperaSafari
+

基本支援

+
{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [2]{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [1]
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
平台AndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
+

基本支援

+
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] 一些瀏覽器在解析日期時間會發生問題: 3/14/2012 blog from danvk Comparing FF/IE/Chrome on Parsing Date Strings

+ +

[2] ISO8601 Date Format is not supported in Internet Explorer 8, and other version can have issues when parsing dates

diff --git a/files/zh-tw/web/javascript/reference/global_objects/date/now/index.html b/files/zh-tw/web/javascript/reference/global_objects/date/now/index.html new file mode 100644 index 0000000000..00b4842f0f --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/date/now/index.html @@ -0,0 +1,123 @@ +--- +title: Date.now() +slug: Web/JavaScript/Reference/Global_Objects/Date/now +tags: + - Date + - JavaScript + - 參考 + - 方法 + - 方法補完 +translation_of: Web/JavaScript/Reference/Global_Objects/Date/now +--- +
{{JSRef}}
+ +

Date.now() 方法回傳自 1970/01/01 00:00:00 UTC 起經過的毫秒數。

+ +

格式

+ +
var timeInMs = Date.now();
+ +

回傳值

+ +

一個代表由經 UNIX 紀元起經過的毫秒數值({{jsxref("Number")}})。

+ +

描述

+ +

由於 now() 是 {{jsxref("Date")}} 的靜態方法,你只能用 Date.now() 的方式呼叫它。

+ +

補完

+ +

這個函數是 ECMA-262 第 5 版的標準。 對於未更新支援此方法的引擎,可以利用底下的程式補上:

+ +
if (!Date.now) {
+  Date.now = function now() {
+    return new Date().getTime();
+  };
+}
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態
{{SpecName('ES5.1', '#sec-15.9.4.4', 'Date.now')}}{{Spec2('ES5.1')}}初始定義,實作在 JavaScript 1.5 。
{{SpecName('ES6', '#sec-date.now', 'Date.now')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-date.now', 'Date.now')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
平台ChromeFirefox (Gecko)Internet ExplorerOperaSafari
基本支援{{CompatChrome("5")}}{{CompatGeckoDesktop("1.9")}}{{CompatIE("9")}}{{CompatOpera("10.50")}}{{CompatSafari("4")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
平台AndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支援{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

相關資源

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/date/prototype/index.html b/files/zh-tw/web/javascript/reference/global_objects/date/prototype/index.html new file mode 100644 index 0000000000..edd6a3fb47 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/date/prototype/index.html @@ -0,0 +1,245 @@ +--- +title: Date.prototype +slug: Web/JavaScript/Reference/Global_Objects/Date/prototype +tags: + - Date + - JavaScript + - 原型 + - 參考資料 + - 屬性 +translation_of: Web/JavaScript/Reference/Global_Objects/Date +--- +
{{JSRef}}
+ +

Date.prototype 屬性表示 {{jsxref("Date")}} 建構子的原型。

+ +
{{js_property_attributes(0, 0, 1)}}
+ +

描述

+ +

JavaScript {{jsxref("Date")}} 實體繼承自 Date.prototype。你可以藉由改變建構子的原型物件,來影響所有繼承自 JavaScript {{jsxref("Date")}} 的實體。

+ +

為了千年年份(換個說法,考慮現在已到了 2000 年)的相容性,設定上你應該採用完整的年份。舉例來說,使用 1998 而不是 98 。為了讓你能取得完整的年份資料, Javascript 包含了 {{jsxref("Date.prototype.getFullYear()", "getFullYear()")}} , {{jsxref("Date.prototype.setFullYear()", "setFullYear()")}} , {{jsxref("Date.prototype.getUTCFullYear()", "getUTCFullYear()")}} 以及 {{jsxref("Date.prototype.setUTCFullYear()", "setUTCFullYear()")}} 方法。

+ +

自 ECMAScript 6 開始, Date.prototype 物件只是個一般物件,而不是一個 {{jsxref("Date")}} 實體。

+ +

屬性

+ +
+
Date.prototype.constructor
+
回傳一個能建立實體的函數,這是 {{jsxref("Date")}} 預設的建構子。
+
+ +

方法

+ +

Getter

+ +
+
{{jsxref("Date.prototype.getDate()")}}
+
回傳本地時間月份中的日期(1-31)。
+
{{jsxref("Date.prototype.getDay()")}}
+
回傳本地時間星期中的日子(0-6)。
+
{{jsxref("Date.prototype.getFullYear()")}}
+
回傳本地時間的年份( 以 4 位數表現)。
+
{{jsxref("Date.prototype.getHours()")}}
+
回傳本地時間的小時(0-23)。
+
{{jsxref("Date.prototype.getMilliseconds()")}}
+
回傳本地時間的毫秒數(0-999)。
+
{{jsxref("Date.prototype.getMinutes()")}}
+
回傳本地時間的分鐘數(0-59)。
+
{{jsxref("Date.prototype.getMonth()")}}
+
回傳本地時間的月份(0-11)。
+
{{jsxref("Date.prototype.getSeconds()")}}
+
回傳本地時間的秒數(0-59)。
+
{{jsxref("Date.prototype.getTime()")}}
+
回傳由 1970-01-01 00:00:00 UTC 開始,到代表時間經過的毫秒數(以負值表示 1970 年之前的時間)。
+
{{jsxref("Date.prototype.getTimezoneOffset()")}}
+
回傳本地時差為多少分鐘。
+
{{jsxref("Date.prototype.getUTCDate()")}}
+
回傳標準時間的在月份中的日期(1-31)。
+
{{jsxref("Date.prototype.getUTCDay()")}}
+
回傳標準時間在星期中的日子(0-6)。
+
{{jsxref("Date.prototype.getUTCFullYear()")}}
+
回傳標準時間的年份( 以 4 位數表現)。
+
{{jsxref("Date.prototype.getUTCHours()")}}
+
回傳標準時間的小時數(0-23)。
+
{{jsxref("Date.prototype.getUTCMilliseconds()")}}
+
回傳標準時間裡的毫秒數(0-999)。
+
{{jsxref("Date.prototype.getUTCMinutes()")}}
+
回傳標準時間的分鐘數(0-59)。
+
{{jsxref("Date.prototype.getUTCMonth()")}}
+
回傳標準時間的月份數(0-11)。
+
{{jsxref("Date.prototype.getUTCSeconds()")}}
+
回傳標準時間的秒數(0-59)。
+
{{jsxref("Date.prototype.getYear()")}} {{deprecated_inline}}
+
回本地時間的年份(通常 2-3 位數)。用 {{jsxref("Date.prototype.getFullYear()", "getFullYear()")}} 取代。
+
+ +

Setter

+ +
+
{{jsxref("Date.prototype.setDate()")}}
+
設定本地時間月份中的日期。
+
{{jsxref("Date.prototype.setFullYear()")}}
+
設定本地時間的完整年份(以 4 位數表達 4 位數年份)。
+
{{jsxref("Date.prototype.setHours()")}}
+
設定本地時間的小時數。
+
{{jsxref("Date.prototype.setMilliseconds()")}}
+
設定本地時間的毫秒數。
+
{{jsxref("Date.prototype.setMinutes()")}}
+
設定本地時間的分鐘數。
+
{{jsxref("Date.prototype.setMonth()")}}
+
設定本地時間的月份。
+
{{jsxref("Date.prototype.setSeconds()")}}
+
設定本地時間的秒數。
+
{{jsxref("Date.prototype.setTime()")}}
+
設定這個 {{jsxref("Date")}} 物件距 1970-01-01 00:00:00 UTC 的毫秒數,允許使用負值表示之前的時間。
+
{{jsxref("Date.prototype.setUTCDate()")}}
+
設定標準時間月份中的日期。
+
{{jsxref("Date.prototype.setUTCFullYear()")}}
+
設定標準時間的完整年份(以 4 位數表示 4 位數年分)。
+
{{jsxref("Date.prototype.setUTCHours()")}}
+
設定標準時間的小時數。
+
{{jsxref("Date.prototype.setUTCMilliseconds()")}}
+
設定標準時間的毫秒數。
+
{{jsxref("Date.prototype.setUTCMinutes()")}}
+
設定標準時間的分鐘數。
+
{{jsxref("Date.prototype.setUTCMonth()")}}
+
設定標準時間的月份數。
+
{{jsxref("Date.prototype.setUTCSeconds()")}}
+
設定標準時間的秒數。
+
{{jsxref("Date.prototype.setYear()")}} {{deprecated_inline}}
+
設定本地時間的年份(使用 2-3 位數)。使用 {{jsxref("Date.prototype.setFullYear()", "setFullYear()")}} 取代。
+
+ +

Conversion getter

+ +
+
{{jsxref("Date.prototype.toDateString()")}}
+
以可閱讀的字串型式,回傳 {{jsxref("Date")}} 的部分資訊。
+
{{jsxref("Date.prototype.toISOString()")}}
+
將日期時間轉換成 ISO 8601 格式的字串回傳。
+
{{jsxref("Date.prototype.toJSON()")}}
+
回傳等義於 {{jsxref("Date")}} 物件使用 {{jsxref("Date.prototype.toISOString()", "toISOString()")}} 方法的結果。特別使用 {{jsxref("JSON.stringify()")}} 處理。
+
{{jsxref("Date.prototype.toGMTString()")}} {{deprecated_inline}}
+
回傳 {{jsxref("Date")}} 以 GMT (UT) 時區基準代表的時間字串。使用 {{jsxref("Date.prototype.toUTCString()", "toUTCString()")}} 方法來取代。
+
{{jsxref("Date.prototype.toLocaleDateString()")}}
+
依照系統的時間地區設定,回傳日期字串。
+
{{jsxref("Date.prototype.toLocaleFormat()")}} {{non-standard_inline}}
+
傳入格式化字串參數,將日期時間轉換成指定格式的字串。
+
{{jsxref("Date.prototype.toLocaleString()")}}
+
回傳依系統的地區設定導出的日期時間字串。覆寫自 {{jsxref("Object.prototype.toLocaleString()")}} 方法。
+
{{jsxref("Date.prototype.toLocaleTimeString()")}}
+
回傳依系統的地區設定導出的時間字串。
+
{{jsxref("Date.prototype.toSource()")}} {{non-standard_inline}}
+
回傳一個建立相同 {{jsxref("Date")}} 物件的程式碼字串;你可以拿這個結果來建立新物件。覆寫自 {{jsxref("Object.prototype.toSource()")}} 方法。
+
{{jsxref("Date.prototype.toString()")}}
+
回傳代表此 {{jsxref("Date")}} 物件的字串。覆寫自 {{jsxref("Object.prototype.toString()")}} 方法。
+
{{jsxref("Date.prototype.toTimeString()")}}
+
以人類可讀的格式,回傳時間部分的字串。
+
{{jsxref("Date.prototype.toUTCString()")}}
+
依 UTC 時區,轉換出時間日期字串。
+
{{jsxref("Date.prototype.valueOf()")}}
+
回傳 {{jsxref("Date")}} 物件的原始數值。覆寫自 {{jsxref("Object.prototype.valueOf()")}} 方法。
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態
{{SpecName('ES1')}}{{Spec2('ES1')}}初步定義。實作在 JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.9.5', 'Date.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-the-date-prototype-object', 'Date.prototype')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-properties-of-the-date-prototype-object', 'Date.prototype')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
平台ChromeFirefox (Gecko)Internet ExplorerOperaSafari
基本支援{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
一般物件{{CompatUnknown}}{{CompatGeckoDesktop("41")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
平台AndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支援{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
一般物件{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("41")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
diff --git a/files/zh-tw/web/javascript/reference/global_objects/date/utc/index.html b/files/zh-tw/web/javascript/reference/global_objects/date/utc/index.html new file mode 100644 index 0000000000..60f1c555f0 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/date/utc/index.html @@ -0,0 +1,157 @@ +--- +title: Date.UTC() +slug: Web/JavaScript/Reference/Global_Objects/Date/UTC +tags: + - Date + - JavaScript + - 參考 + - 方法 +translation_of: Web/JavaScript/Reference/Global_Objects/Date/UTC +--- +
{{JSRef}}
+ +

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 之間。
+
+ +

回傳值

+ +

得到傳入這個 {{jsxref("Date")}} 方法的參數所代表時間,與 1970-01-01 00:00:00 UTC 相差的毫秒數。

+ +

描述

+ +

UTC() 取得以逗號分隔的時間參數,回傳 1970-01-01 00:00:00 UTC 與該時間相差的毫秒數。

+ +

你應該指定完成的年份資料,例如: 1998。如果一個 0 到 99 的年份被指定,這個方法會將它轉換為 20 世紀的年份(變為 19xx 年),例如你傳入 95 ,則會被當作 1995 年被指定。

+ +

這個 UTC() 方法與 {{jsxref("Date")}} 建構子有兩個地方不同。

+ + + +

當你指定參數超出預期的範圍, UTC( ) 方法會去調整其它的參數使之成立。比如如果你指定月份為 15 ,年份將被加 1 ,以 3 作為傳入的月份。

+ +

因為 UTC( ) 是 {{jsxref("Date")}} 的一個靜態方法,只能使用 Date.UTC() 的方式呼叫,而不能由建立出來的 {{jsxref("Date")}} 物件去執行它。

+ +

範例

+ +

使用 Date.UTC()

+ +

以下利用它來將指定的時間以 UTC 而非本地時間的方式來建立  {{jsxref("Date")}} 物件:

+ +
var utcDate = new Date(Date.UTC(96, 11, 1, 0, 0, 0));
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態
{{SpecName('ESDraft', '#sec-date.utc', 'Date.UTC')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-date.utc', 'Date.UTC')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.9.4.3', 'Date.UTC')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}}初始定義。
+ 實作在 JavaScript 1.0.
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
平台ChromeFirefox (Gecko)Internet ExplorerOperaSafari
基本支援{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
平台AndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支援{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

相關資源

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/error/columnnumber/index.html b/files/zh-tw/web/javascript/reference/global_objects/error/columnnumber/index.html new file mode 100644 index 0000000000..1db87220e8 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/error/columnnumber/index.html @@ -0,0 +1,81 @@ +--- +title: Error.prototype.columnNumber +slug: Web/JavaScript/Reference/Global_Objects/Error/columnNumber +translation_of: Web/JavaScript/Reference/Global_Objects/Error/columnNumber +--- +
{{JSRef}} {{non-standard_header}}
+ +

「行數」屬性含括了檔案中引起錯誤的所在行數。

+ +

範例

+ +

使用 columnNumber

+ +
var e = new Error('Could not parse input');
+throw e;
+console.log(e.columnNumber) // 0
+
+ +

規格

+ +

不是任何規格的一部份,尚未標準化。

+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

See also

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/error/index.html b/files/zh-tw/web/javascript/reference/global_objects/error/index.html new file mode 100644 index 0000000000..623a5dfeac --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/error/index.html @@ -0,0 +1,233 @@ +--- +title: Error +slug: Web/JavaScript/Reference/Global_Objects/Error +tags: + - Error + - JavaScript + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Error +--- +
{{JSRef}}
+ +

Error 建構函式能用來建立一個 error 物件。當執行期間發生錯誤時,Error 物件實體會被拋出。Error 物件也可作為自訂例外的基礎物件,請參考下方的標準內建錯誤類型。

+ +

語法

+ +
new Error([message[, fileName[, lineNumber]]])
+ +

參數

+ +
+
message {{optional_inline}}
+
人們可閱讀的錯誤說明。
+
fileName {{optional_inline}} {{non-standard_inline}}
+
The value for the fileName property on the created Error object. Defaults to the name of the file containing the code that called the Error() constructor.
+
lineNumber {{optional_inline}} {{non-standard_inline}}
+
Optional. The value for the lineNumber property on the created Error object. Defaults to the line number containing the Error() constructor invocation.
+
+ +

描述

+ +

Runtime errors result in new Error objects being created and thrown.

+ +

This page documents the use of the Error object itself and its use as a constructor function. For a list of properties and methods inherited by Error instances, see {{jsxref("Error.prototype")}}.

+ +

錯誤類型

+ +

Besides the generic Error constructor, there are six other core error constructors in JavaScript. For client-side exceptions, see Exception Handling Statements.

+ +
+
{{jsxref("EvalError")}}
+
Creates an instance representing an error that occurs regarding the global function {{jsxref("Global_Objects/eval", "eval()")}}.
+
{{jsxref("InternalError")}} {{non-standard_inline}}
+
Creates an instance representing an error that occurs when an internal error in the JavaScript engine is thrown. E.g. "too much recursion".
+
{{jsxref("RangeError")}}
+
Creates an instance representing an error that occurs when a numeric variable or parameter is outside of its valid range.
+
{{jsxref("ReferenceError")}}
+
Creates an instance representing an error that occurs when de-referencing an invalid reference.
+
{{jsxref("SyntaxError")}}
+
Creates an instance representing a syntax error that occurs while parsing code in {{jsxref("Global_Objects/eval", "eval()")}}.
+
{{jsxref("TypeError")}}
+
Creates an instance representing an error that occurs when a variable or parameter is not of a valid type.
+
{{jsxref("URIError")}}
+
Creates an instance representing an error that occurs when {{jsxref("Global_Objects/encodeURI", "encodeURI()")}} or {{jsxref("Global_Objects/decodeURI", "decodeURI()")}} are passed invalid parameters.
+
+ +

屬性

+ +
+
{{jsxref("Error.prototype")}}
+
Allows the addition of properties to Error instances.
+
+ +

方法

+ +

The global Error object contains no methods of its own, however, it does inherit some methods through the prototype chain.

+ +

Error 實體

+ +
{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Description')}}
+ +

屬性

+ +
{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Properties')}}
+ +

方法

+ +
{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Methods')}}
+ +

範例

+ +

Throwing a generic error

+ +

Usually you create an Error object with the intention of raising it using the {{jsxref("Statements/throw", "throw")}} keyword. You can handle the error using the {{jsxref("Statements/try...catch", "try...catch")}} construct:

+ +
try {
+  throw new Error('Whoops!');
+} catch (e) {
+  console.log(e.name + ': ' + e.message);
+}
+
+ +

Handling a specific error

+ +

You can choose to handle only specific error types by testing the error type with the error's {{jsxref("Object.prototype.constructor", "constructor")}} property or, if you're writing for modern JavaScript engines, {{jsxref("Operators/instanceof", "instanceof")}} keyword:

+ +
try {
+  foo.bar();
+} catch (e) {
+  if (e instanceof EvalError) {
+    console.log(e.name + ': ' + e.message);
+  } else if (e instanceof RangeError) {
+    console.log(e.name + ': ' + e.message);
+  }
+  // ... etc
+}
+
+ +

Custom Error Types

+ +

You might want to define your own error types deriving from Error to be able to throw new MyError() and use instanceof MyError to check the kind of error in the exception handler. The common way to do this is demonstrated below.

+ +
+

Note that the thrown MyError will report incorrect lineNumber and fileName at least in Firefox.

+
+ +

See also the "What's a good way to extend Error in JavaScript?" discussion on Stackoverflow.

+ +
// Create a new object, that prototypically inherits from the Error constructor
+function MyError(message) {
+  this.name = 'MyError';
+  this.message = message || 'Default Message';
+  this.stack = (new Error()).stack;
+}
+MyError.prototype = Object.create(Error.prototype);
+MyError.prototype.constructor = MyError;
+
+try {
+  throw new MyError();
+} catch (e) {
+  console.log(e.name);     // 'MyError'
+  console.log(e.message);  // 'Default Message'
+}
+
+try {
+  throw new MyError('custom message');
+} catch (e) {
+  console.log(e.name);     // 'MyError'
+  console.log(e.message);  // 'custom message'
+}
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.11', 'Error')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-error-objects', 'Error')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-error-objects', 'Error')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/function/apply/index.html b/files/zh-tw/web/javascript/reference/global_objects/function/apply/index.html new file mode 100644 index 0000000000..698d2f46fc --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/function/apply/index.html @@ -0,0 +1,260 @@ +--- +title: Function.prototype.apply() +slug: Web/JavaScript/Reference/Global_Objects/Function/apply +translation_of: Web/JavaScript/Reference/Global_Objects/Function/apply +--- +
{{JSRef}}
+ +

apply() 方法會呼叫一個以 this 的代表值和一個陣列形式的值組(或是一個 array-like object )為參數的函式。

+ +
+

注意:這個函式的語法和{{jsxref("Function.call", "call()")}} 幾乎一樣,最大的不同是 call() 接受一連串的參數,而 apply() 接受一組陣列形式的參數

+
+ +

語法

+ +
fun.apply(thisArg, [argsArray])
+ +

參數

+ +
+
thisArg
+
讓 fun 呼叫時可以視為 this  的值。注意,這可能並不是最後會在方法裡看見的值:如果這是一個在非 {{jsxref("Strict_mode", "non-strict mode", "", 1)}} 下運作的程式碼,{{jsxref("null")}} 及 {{jsxref("undefined")}} 將會被全域物件取代,而原始類別將被封裝。
+
argsArray
+
一個 array-like object ,定義了 fun 要呼叫的一組參數,如果沒有需要提供,可以傳入 {{jsxref("null")}} 或 {{jsxref("undefined")}} 。從 ECMAScript 5 開始,這些參數不僅可以是泛型的 array-like object ,而不一定要是一組陣列。查看下方的{{anch("Browser_compatibility", "browser compatibility")}} 資訊。
+
+ +

回傳值

+ +

傳入 this 值及一組參數後得到的結果。

+ +

描述

+ +

在呼叫一個現存的函式時,你可以傳入不同的 this 物件值。this 參考到現在的物件,也就是正在執行的物件。apply 讓你可以只寫一次方法後,讓其他物件也繼承到這個方法,而不用一再重寫。

+ +

apply 與 {{jsxref("Function.call", "call()")}} 非常相似,不同的是支援的傳入參數類型。使用陣列形式的參數,而不是命名過的接收參數。使用 apply 時,你可以選擇使用陣列實字:fun.apply(this, ['eat', 'bananas']); 或是 {{jsxref("Array")}} 物件: fun.apply(this, new Array('eat', 'bananas'))。

+ +

除此之外,你也可以使用 {{jsxref("Functions/arguments", "arguments")}} 代表 argsArray 參數。arguments 是在函式裡的區域變數,可用來存取所有沒有特別被所呼叫物件指定的傳入參數。因此,使用 apply 時你不需要知道所呼叫函式的指定參數。使用 arguments 把所有參數傳入呼叫的方法裡,而被呼叫的方法會接手處理這些參數。

+ +

從 ECMAScript 5th 版本後,也可以使用陣列形式的物件,在實踐上這代表他會擁有 length 以及整數範圍  (0...length-1) 的屬性。舉例來說,你可以使用 {{domxref("NodeList")}}  或是一個像這樣的自定義屬性: { 'length': 2, '0': 'eat', '1': 'bananas' }。

+ +
+

一般瀏覽器,包括 Chrome 14 及 Internet Explorer 9,仍不支援陣列形式的物件,所以會對此丟出一個錯誤。

+
+ +

範例

+ +

使用 apply 與建構子鏈結

+ +

您可以使用 apply 鏈結 {{jsxref("Operators/new", "constructors", "", 1)}} 一個物件,與 Java 相似,如下範例中我們可以建立一個全域的 {{jsxref("Function")}} 方法叫 construct,使您可以使用類陣列的物件與建構子去替代參數列表。

+ +
Function.prototype.construct = function(aArgs) {
+  var oNew = Object.create(this.prototype);
+  this.apply(oNew, aArgs);
+  return oNew;
+};
+
+ +
+

注意:如上範例的 Object.create() 方法是屬於比較新的寫法。如需使用閉包的替代方法,請參考以下的範例:

+ +
Function.prototype.construct = function(aArgs) {
+  var fConstructor = this, fNewConstr = function() {
+    fConstructor.apply(this, aArgs);
+  };
+  fNewConstr.prototype = fConstructor.prototype;
+  return new fNewConstr();
+};
+
+ +

使用範例:

+ +
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 {{jsxref("Date")}}, for example). In these cases you have to use the {{jsxref("Function.prototype.bind")}} method (for example, imagine having an array like the following, to be used with {{jsxref("Global_Objects/Date", "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 來找出陣列中最大/最小的值。

+ +
// 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:

+ +
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:

+ +
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).

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.3.4.3', 'Function.prototype.apply')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-function.prototype.apply', 'Function.prototype.apply')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-function.prototype.apply', 'Function.prototype.apply')}}{{Spec2('ESDraft')}}
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
ES 5.1 generic array-like object as {{jsxref("Functions/arguments", "arguments")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
ES 5.1 generic array-like object as {{jsxref("Functions/arguments", "arguments")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("2.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/function/bind/index.html b/files/zh-tw/web/javascript/reference/global_objects/function/bind/index.html new file mode 100644 index 0000000000..7092477133 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/function/bind/index.html @@ -0,0 +1,321 @@ +--- +title: Function.prototype.bind() +slug: Web/JavaScript/Reference/Global_Objects/Function/bind +translation_of: Web/JavaScript/Reference/Global_Objects/Function/bind +--- +
{{JSRef}}
+ +

bind() 方法,會建立一個新函式。該函式被呼叫時,會將 this 關鍵字設為給定的參數,並在呼叫時,帶有提供之前,給定順序的參數。

+ +

語法

+ +
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 {{jsxref("Operators/new", "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 objectECMAScript 2015 的術語)。通常,呼叫 BF 會執行該 wrapped function BF 含有以下內部屬性:

+ + + +

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:

+ +
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.

+ +
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 {{domxref("window.setTimeout()")}}, the this keyword will be set to the {{ domxref("window") }} (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.

+ +
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

+ +
+

Warning: 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 {{jsxref("Operators/new", "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:

+ +
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 {{jsxref("Operators/new", "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 {{jsxref("Operators/new", "new")}}.

+ +
// 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 {{jsxref("Operators/new", "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 {{jsxref("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:

+ +
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 {{jsxref("Function.prototype.apply()", "apply()")}} function of {{jsxref("Function.prototype")}}, with the this value set to the {{jsxref("Array.prototype.slice()", "slice()")}} function of {{jsxref("Array.prototype")}}. This means that additional apply() calls can be eliminated:

+ +
// 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.

+ +
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:

+ + + +

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!

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.3.4.5', 'Function.prototype.bind')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES2015', '#sec-function.prototype.bind', 'Function.prototype.bind')}}{{Spec2('ES2015')}} 
{{SpecName('ESDraft', '#sec-function.prototype.bind', 'Function.prototype.bind')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("7")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("2")}}{{CompatIE("9")}}{{CompatOpera("11.60")}}{{CompatSafari("5.1")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatAndroid("4.0")}}{{CompatChrome("1")}}{{CompatVersionUnknown}}{{CompatGeckoMobile("2")}}{{CompatUnknown}}{{CompatOperaMobile("11.5")}}{{CompatSafari("6.0")}}
+
+ +

相關連結

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/function/call/index.html b/files/zh-tw/web/javascript/reference/global_objects/function/call/index.html new file mode 100644 index 0000000000..1d1d2017ee --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/function/call/index.html @@ -0,0 +1,105 @@ +--- +title: Function.prototype.call +slug: Web/JavaScript/Reference/Global_Objects/Function/call +translation_of: Web/JavaScript/Reference/Global_Objects/Function/call +--- +

{{JSRef}}

+ +

概述

+ +

使用給定的this參數以及分別給定的參數來呼叫某個函數

+ +
附註: 此函數的所有語法大致上與apply()相同,他們基本上不同處只有 call() 接受一連串的參數,而 apply() 單一的array作為參數
+ + + + + + + + + + + + + + + + + +
Function 物件的方法
被實作於JavaScript 1.3
ECMAScript 版本ECMAScript 第三版
+ +

語法

+ +
fun.call(thisArg[, arg1[, arg2[, ...]]])
+ +

參數

+ +
+
thisArg
+
呼叫fun時提供的this值。 注意,它可能是一個無法在函數內看到的值:若這個函數是在非嚴苛模式( non-strict mode ), null 、undefined 將會被置換成全域變數,而原生型態的值將會被封裝
+
arg1, arg2, ...
+
其他參數
+
+ +

描述

+ +

你可以在呼叫一個現存的函數時,使用不一樣的 this 物件。 this 會參照到目前的物件,呼叫的物件上

+ +

使用 call, 你可以實作函數一次,然後在其他的物件上直接繼承它,而不用在新的物件上重寫該函數

+ +

範例

+ +

使用 call 來串接物件上的建構子

+ +

你可以使用 call 來串接其他物件的建構子,就像 Java. 下面的例子中,Product 物件的建構子定義了兩個參數 name 以及 price. 其他函數FoodToy 引用了 Product 並傳入 thisnameprice。 Product 初始化它的屬性 nameprice, 而兩個子函數則定義了category。

+ +
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 的值並不是必要的,但他有解釋的用途。

+ +
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);
+}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/function/index.html b/files/zh-tw/web/javascript/reference/global_objects/function/index.html new file mode 100644 index 0000000000..b88c087b24 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/function/index.html @@ -0,0 +1,191 @@ +--- +title: Function +slug: Web/JavaScript/Reference/Global_Objects/Function +tags: + - JavaScript + - JavaScript Reference + - NeedsTranslation + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Function +--- +
{{JSRef}}
+ +

Function 建構函式可建立一個新的 Function 物件。在 JavaScript 中,所有的函式實際上都是 Function 物件。

+ +

語法

+ +
new Function ([arg1[, arg2[, ...argN]],] functionBody)
+ +

參數

+ +
+
arg1, arg2, ... argN
+
function 的引數名稱必須要符合正規的命名。每個名稱都必須要是有效的 JavaScript 識別符號規則的字串,或是使用英文逗號「, 」分隔開的字串清單; 像是 "x", "theValue", 或是 "a, b'。
+
functionBody
+
包含 JavaScript 狀態以及 function 定義的字串。
+
+ +

描述

+ +

Function objects created with the Function constructor are parsed when the function is created. This is less efficient than declaring a function with a function expression or function statement and calling it within your code, because such functions are parsed with the rest of the code.

+ +

All arguments passed to the function are treated as the names of the identifiers of the parameters in the function to be created, in the order in which they are passed.

+ +

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

+ +

Function 的屬性與方法

+ +

The global Function object has no methods or properties of its own, however, since it is a function itself it does inherit some methods and properties through the prototype chain from {{jsxref("Function.prototype")}}.

+ +

Function 原型物件

+ +

屬性 Properties

+ +
{{page('/zh-TW/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Properties')}}
+ +

方法 Methods

+ +
{{page('/zh-TW/docs/JavaScript/Reference/Global_Objects/Function/prototype', 'Methods')}}
+ +

Function 實例

+ +

Function instances inherit methods and properties from {{jsxref("Function.prototype")}}. As with all constructors, you can change the constructor's prototype object to make changes to all Function instances.

+ +

範例

+ +

Specifying arguments with the Function constructor

+ +

The following code creates a Function object that takes two arguments.

+ +
// Example can be run directly in your JavaScript console
+
+// Create a function that takes two arguments and returns the sum of those arguments
+var adder = new Function('a', 'b', 'return a + b');
+
+// Call the function
+adder(2, 6);
+// > 8
+
+ +

The arguments "a" and "b" are formal argument names that are used in the function body, "return a + b".

+ +

Difference between Function constructor and function declaration

+ +

Functions created with the Function constructor do not create closures to their creation contexts; they always are created in the global scope. When running them, they will only be able to access their own local variables and global ones, not the ones from the scope in which the Function constructor was called. This is different from using {{jsxref("eval")}} with code for a function expression.

+ +
var x = 10;
+
+function createFunction1() {
+    var x = 20;
+    return new Function('return x;'); // this |x| refers global |x|
+}
+
+function createFunction2() {
+    var x = 20;
+    function f() {
+        return x; // this |x| refers local |x| above
+    }
+    return f;
+}
+
+var f1 = createFunction1();
+console.log(f1());          // 10
+var f2 = createFunction2();
+console.log(f2());          // 20
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.3', 'Function')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-objects', 'Function')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-function-objects', 'Function')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/function/length/index.html b/files/zh-tw/web/javascript/reference/global_objects/function/length/index.html new file mode 100644 index 0000000000..699e1ff178 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/function/length/index.html @@ -0,0 +1,144 @@ +--- +title: Function.length +slug: Web/JavaScript/Reference/Global_Objects/Function/length +translation_of: Web/JavaScript/Reference/Global_Objects/Function/length +--- +
{{JSRef}}
+ +

length property表示該 function 預期被傳入的參數數量

+ +
{{js_property_attributes(0,0,1)}}
+ +

描述

+ +

length 是 function 物件的一個 property,表示該 function 預期被傳入的參數數量,這個數量並不包含 {{jsxref("rest_parameters", "rest parameter", "", 1)}} 且只包涵第一個預設參數(Default Parameters)前的參數。相較之下 {{jsxref("Functions_and_function_scope/arguments/length", "arguments.length")}} 是 function 內部的物件,會提供真正傳進 function 中的參數數量。

+ +

Function 建構子的 data property

+ +

{{jsxref("Function")}} 建構子本身就是一個 {{jsxref("Function")}} 物件。其 length data property 的值為 1。此 property 的 attributes 包含: Writable: false, Enumerable: false, Configurable: true.

+ +

Function prototype 物件的 property

+ +

{{jsxref("Function")}} prototype 物件的 length property 其值為 0。

+ +

範例

+ +
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
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態註釋
{{SpecName('ES1')}}{{Spec2('ES1')}}最初的定義,在 JavaScript 1.1 中實作。
{{SpecName('ES5.1', '#sec-15.3.5.1', 'Function.length')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-instances-length', 'Function.length')}}{{Spec2('ES6')}}此 property 的 configurable attribute 現在為 true.
{{SpecName('ESDraft', '#sec-function-instances-length', 'Function.length')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
特點ChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Configurable: true{{CompatUnknown}}{{CompatGeckoDesktop(37)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Configurable: true{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile(37)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

可參閱

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/function/prototype/index.html b/files/zh-tw/web/javascript/reference/global_objects/function/prototype/index.html new file mode 100644 index 0000000000..1db46bc59a --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/function/prototype/index.html @@ -0,0 +1,138 @@ +--- +title: Function.prototype +slug: Web/JavaScript/Reference/Global_Objects/Function/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Function +--- +
{{JSRef}}
+ +

Function.prototype 屬性表示 {{jsxref("Function")}} 的原型物件。

+ +

描述

+ +

{{jsxref("Function")}} objects inherit from Function.prototypeFunction.prototype cannot be modified.

+ +

屬性

+ +
+
{{jsxref("Function.arguments")}} {{deprecated_inline}}
+
An array corresponding to the arguments passed to a function. This is deprecated as property of {{jsxref("Function")}}, use the {{jsxref("Functions/arguments", "arguments")}} object available within the function instead.
+
{{jsxref("Function.arity")}} {{obsolete_inline}}
+
Used to specifiy the number of arguments expected by the function, but has been removed. Use the {{jsxref("Function.length", "length")}} property instead.
+
{{jsxref("Function.caller")}} {{non-standard_inline}}
+
Specifies the function that invoked the currently executing function.
+
{{jsxref("Function.length")}}
+
Specifies the number of arguments expected by the function.
+
{{jsxref("Function.name")}}
+
The name of the function.
+
{{jsxref("Function.displayName")}} {{non-standard_inline}}
+
The display name of the function.
+
Function.prototype.constructor
+
Specifies the function that creates an object's prototype. See {{jsxref("Object.prototype.constructor")}} for more details.
+
+ +

方法

+ +
+
{{jsxref("Function.prototype.apply()")}}
+
Calls a function and sets its this to the provided value, arguments can be passed as an {{jsxref("Array")}} object.
+
{{jsxref("Function.prototype.bind()")}}
+
Creates a new function which, when called, has its this set to the provided value, with a given sequence of arguments preceding any provided when the new function was called.
+
{{jsxref("Function.prototype.call()")}}
+
Calls (executes) a function and sets its this to the provided value, arguments can be passed as they are.
+
{{jsxref("Function.prototype.isGenerator()")}} {{non-standard_inline}}
+
Returns true if the function is a generator; otherwise returns false.
+
{{jsxref("Function.prototype.toSource()")}} {{non-standard_inline}}
+
Returns a string representing the source code of the function. Overrides the {{jsxref("Object.prototype.toSource")}} method.
+
{{jsxref("Function.prototype.toString()")}}
+
Returns a string representing the source code of the function. Overrides the {{jsxref("Object.prototype.toString")}} method.
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1
{{SpecName('ES5.1', '#sec-15.3.5.2', 'Function.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-instances-prototype', 'Function.prototype')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-function-instances-prototype', 'Function.prototype')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/index.html b/files/zh-tw/web/javascript/reference/global_objects/index.html new file mode 100644 index 0000000000..c9e81579fb --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/index.html @@ -0,0 +1,201 @@ +--- +title: 標準內建物件 +slug: Web/JavaScript/Reference/Global_Objects +tags: + - JavaScript + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects +--- +
{{jsSidebar("Objects")}}
+ +

本章節記錄了 JavaScript 所有標準、內建的物件,以及這些物件的方法與屬性。

+ +

「全域物件」(或稱作標準內建物件)這個專有名字並非是要和全域物件混著說。在這裡,全域物件是那些在全域範圍裡的物件。而全域物件自身則是關聯到全域範圍裡的 {{jsxref("Operators/this", "this")}} 運算子(但若是在 ECMAScript 5 的嚴格模式(strict mode)則是不被採用的,即會回傳 {{jsxref("undefined")}})。 事實上,全域範圍包含了全域物件的屬性,也包含了繼承而來的屬性(如果有的話)。

+ +

其他在全域範疇的物件,不是被使用者的腳本建立,就是由主體的應用程式所提供。 主體物件是由 API 參考資料定義的文件決定瀏覽器環境中是否可用。 更多關於 DOMJavaScript 核心的差異,請參考 JavaScript 技術概要

+ +

標準物件分類

+ +

數值屬性

+ +

這些全域屬性會返回一個值;全域屬性本身不擁有任何屬性和函式。

+ + + +

函數屬性

+ +

這些全域函式會直接在全域範圍中被呼叫,不用從某個物件取得後呼叫;呼叫後直接回傳結果給執行的人。

+ + + +

基礎物件

+ +

這裡所陳列稱為基礎物件,將作為其他所有物件的母物件。包含了一般物件、函式以及錯誤。

+ + + +

數字與日期

+ +

這裡陳列了數字、日期及數學運算。

+ + + +

文字處理

+ +

These objects represent strings and support manipulating them.

+ + + +

具索引的集合

+ +

These objects represent collections of data which are ordered by an index value. This includes (typed) arrays and array-like constructs.

+ + + +

具鍵值的集合

+ +

These objects represent collections which use keys; these contain elements which are iterable in the order of insertion.

+ + + +

向量集合

+ +

{{Glossary("SIMD")}} vector data types are objects where data is arranged into lanes.

+ + + +

結構化資料

+ +

These objects represent and interact with structured data buffers and data coded using JavaScript Object Notation (JSON).

+ + + +

控制抽象化物件

+ + + +

Reflection

+ + + +

國際化

+ +

Additions to the ECMAScript core for language-sensitive functionalities.

+ + + +

WebAssembly

+ + + +

非標準物件

+ + + +

其他

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/infinity/index.html b/files/zh-tw/web/javascript/reference/global_objects/infinity/index.html new file mode 100644 index 0000000000..147914eea7 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/infinity/index.html @@ -0,0 +1,76 @@ +--- +title: Infinity +slug: Web/JavaScript/Reference/Global_Objects/Infinity +translation_of: Web/JavaScript/Reference/Global_Objects/Infinity +--- +
{{jsSidebar("Objects")}}
+ +

全域 Infinity 屬性是一個表示無窮大的數值。

+ +

{{js_property_attributes(0,0,0)}}

+ +

語法

+ +
Infinity 
+ +

描述

+ +

Infinity 是全域物件屬性,即它是全域範圍內的變數。

+ +

Infinity 的初始值是 {{jsxref("Number.POSITIVE_INFINITY")}} Infinity 值(正無窮大)值大於其他任何數值。該值在數學上表現為無窮大。例如,任何乘以 Infinity 的正整數都是 Infinity,除以 Infinity 的任何數都是 0。

+ +

按照 ECMAScript 5 規範,在 JavaScript 1.8.5 / Firefox 4 實作的 Infinity 乃唯讀屬性。

+ +

範例

+ +
console.log(Infinity         ); /* Infinity */
+console.log(Infinity + 1     ); /* Infinity */
+console.log(Math.pow(10,1000)); /* Infinity */
+console.log(Math.log(0)      ); /* -Infinity */
+console.log(1 / Infinity     ); /* 0 */
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態註解
{{SpecName('ES1')}}{{Spec2('ES1')}}初始定義。在 JavaScript 1.3 實作。
{{SpecName('ES5.1', '#sec-15.1.1.2', 'Infinity')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-value-properties-of-the-global-object-infinity', 'Infinity')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-value-properties-of-the-global-object-infinity', 'Infinity')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +

{{Compat("javascript.builtins.Infinity")}}

+ + +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/isnan/index.html b/files/zh-tw/web/javascript/reference/global_objects/isnan/index.html new file mode 100644 index 0000000000..6f055cb8fa --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/isnan/index.html @@ -0,0 +1,183 @@ +--- +title: isNaN() +slug: Web/JavaScript/Reference/Global_Objects/isNaN +translation_of: Web/JavaScript/Reference/Global_Objects/isNaN +--- +
{{jsSidebar("Objects")}}
+ +

isNaN() 函式會判斷某個數值是不是 {{jsxref("NaN")}}。注意:在 isNaN 函式裡面,有個有趣的強制性規則。你可能會想改用在 ECMAScript 2015 導入的 {{jsxref("Number.isNaN()")}}。

+ +
{{EmbedInteractiveExample("pages/js/globalprops-isnan.html")}}
+ +

語法

+ +
isNaN(value)
+ +

參數

+ +
+
value
+
要測試的數值。
+
+ +

回傳值

+ +

如果給定值是 {{jsxref("NaN")}} 就回傳 true、否則就回傳 false

+ +

描述

+ +

為什麼要用 isNaN 函式

+ +

與其他 JavaScript 的值不同,你不可能靠等號運算符(== 與 ===)來判斷某個值是不是 {{jsxref("NaN")}},因為連 NaN == NaNNaN === NaN 的結果都是 false。因此,isNaN 函式是必要的。

+ +

NaN 值的來源

+ +

NaN 會在算術運算(arithmetic operations)出現 undefined 或是 unrepresentable 值的結果時產生。這些值不一定是溢出條件。NaN 亦為試圖給毫無可用數字的原始值、予以強制運算之結果。

+ +

例如,零除以零的結果會是 NaN——不過把其他數字除以零則不是 NaN

+ +

令人困惑的特殊狀況行為

+ +

從最早的 isNaN 函式版本規範始,其針對非數值之行為,不斷教人困惑至極。當 isNaN 函式的參數並非數字型別時,此值會先強制轉換到數字。該值接著會測定此值是否為 {{jsxref("NaN")}}。因此,當被強制轉換的非數字,給出了有效的非 NaN 值(經典案例為空的字串與布林原始值:它們在強制轉換時,會給予數字結果 0 或 1)時,會回傳不如預期的「false」值:以空的字串為例,它很明顯地「非數字」。這段教人糾結的點,乃出於「非數字」術語的「數字」一詞、由 IEEE-754 浮點值定義之事實而來。這個函式要解釋為「當這個值,被強制轉換為數值時,它還是 IEEE-754 的『非數字』值嗎?」的答案。

+ +

最新的 ECMAScript(ES2015)版本導入了 {{jsxref("Number.isNaN()")}} 函式。儘管 Number.isNaNNaN 依舊維持了數字上的意義、而不是簡單的「非數字」,Number.isNaN(x) 在偵測 xNaN 與否時比較可靠。另外,如果在缺少 Number.isNaN 的情況下,通過表達式(x != x) 來檢測變量x是否是NaN會更加的可靠。

+ +

一個 isNaN 的 polyfill 可以理解為(這個 polyfill 利用了 NaN 自身永不等於自身這一特性):

+ +
var isNaN = function(value) {
+    var n = Number(value);
+    return n !== n;
+};
+ +

範例

+ +
isNaN(NaN);       // true
+isNaN(undefined); // true
+isNaN({});        // true
+
+isNaN(true);      // false
+isNaN(null);      // false
+isNaN(37);        // false
+
+// 字串
+isNaN("37");      // false: "37" 轉換成數字的 37 後就不是 NaN 了
+isNaN("37.37");   // false: "37.37" 轉換成數字的 37.37 後就不是 NaN 了
+isNaN("123ABC");  // true:  parseInt("123ABC") 是 123 但 Number("123ABC") 是 NaN
+isNaN("");        // false: 空字串轉換成數字的 0 後就不是 NaN 了
+isNaN(" ");       // false: 有空白的字串轉換成數字的 0 後就不是 NaN 了
+
+// 日期
+isNaN(new Date());                // false
+isNaN(new Date().toString());     // true
+
+// 這個偵測的錯誤是不能完全信賴 isNaN 的理由
+isNaN("blabla")   // true: "blabla" 被轉換為數字,將其解析為數字失敗後回傳了 NaN
+
+ +

實用的特殊狀況行為

+ +

當然,你能以更用途導向的方法去思考 isNaN():如果 isNaN() 回傳 false,那麼把 x 用在任何算術表達式都不會回傳 NaN。相反地,如果回傳 true,那麼把 x 用在任何算術表達式都會是 NaN。這在 JavaScript 的意義是 isNaN(x) == true 等於 x - 0 回傳 NaN(儘管在 JavaScript 裡面 x - 0 == NaN 永遠回傳 false,你因而無法測試)──事實上,isNaN(x)isNaN(x - 0)isNaN(Number(x))Number.isNaN(x - 0)Number.isNaN(Number(x)) 在 JavaScript 裡面,都會回傳一樣的東西。而 isNaN(x) 是所有表達式裡面最短的一種。

+ +

比方說,你可以用這個式子,去測試函式的參數能不能透過算術處理(也就是能「像」數字一樣被利用)、否則就提供預設值之類的。你可以透過上下文的根據以隱式數值轉換(implicitly converting values),以使用 JavaScript 提供的全部功能。

+ +

範例

+ +
function increment(x) {
+  if (isNaN(x)) x = 0;
+  return x + 1;
+};
+
+// 與 Number.isNaN() 一樣:
+function increment(x) {
+  if (Number.isNaN(Number(x))) x = 0;
+  return x + 1;
+};
+
+// 以下範例的函式參數 x,isNaN(x) 都會回傳 false,
+// 儘管 x 不是數字,依舊能用在算術表達式。
+increment("");            // 1: "" 被轉換成 0
+increment(new String());  // 1: 空字串的新字串物件被轉換成 0
+increment([]);            // 1: [] 被轉換成 0
+increment(new Array());   // 1: 空陣列的新陣列物件被轉換成 0
+increment("0");           // 1: "0" 被轉換成 0
+increment("1");           // 2: "1" 被轉換成 1
+increment("0.1");         // 1.1: "0.1" 被轉換成 0.1
+increment("Infinity");    // Infinity: "Infinity" 被轉換成 Infinity
+increment(null);          // 1: null 被轉換成 0
+increment(false);         // 1: false 被轉換成 0
+increment(true);          // 2: true 被轉換成 1
+increment(new Date());    // 回傳以毫秒為單位加 1,當今的日期/時間
+
+// 以下範例的函式參數 x,isNaN(x) 都會回傳 false,而 x 的確是數字。
+increment(-1);            // 0
+increment(-0.1);          // 0.9
+increment(0);             // 1
+increment(1);             // 2
+increment(2);             // 3
+// …等等…
+increment(Infinity);      // Infinity
+
+// 以下範例的函式參數 x,isNaN(x) 都會回傳 true,x 也的確不是數字。
+// 使得函式會被 0 取代,並回傳 1
+increment(String);            // 1
+increment(Array);             // 1
+increment("blabla");          // 1
+increment("-blabla");         // 1
+increment(0/0);               // 1
+increment("0/0");             // 1
+increment(Infinity/Infinity); // 1
+increment(NaN);               // 1
+increment(undefined);         // 1
+increment();                  // 1
+
+// isNaN(x) 與 isNaN(Number(x)) 永遠一樣,不過這裡的 x 是強制存在的!
+isNaN(x) == isNaN(Number(x)) // 針對所有 x 的值都是 true,x == undefined 也不例外,
+                             // 因為 isNaN(undefined) == true 且 Number(undefined) 回傳 NaN,
+                             // 不過……
+isNaN() == isNaN(Number())   // false,因為 isNaN() == true 且 Number() == 0
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態註解
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.1.2.4', 'isNaN')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-isnan-number', 'isNaN')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-isnan-number', 'isNaN')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.isNaN")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/json/index.html b/files/zh-tw/web/javascript/reference/global_objects/json/index.html new file mode 100644 index 0000000000..8d3aeadbf2 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/json/index.html @@ -0,0 +1,206 @@ +--- +title: JSON +slug: Web/JavaScript/Reference/Global_Objects/JSON +tags: + - JSON + - JavaScript + - NeedsTranslation + - Object + - Reference + - Référence(2) + - TopicStub + - polyfill +translation_of: Web/JavaScript/Reference/Global_Objects/JSON +--- +
{{JSRef}}
+ +

JSON 物件包含了解析、或是轉換為 JavaScript Object Notation({{glossary("JSON")}})格式的方法。這物件不能被呼叫或建構;而除了它的兩個方法屬性以外,本身也沒有特別的功能。

+ +

描述

+ +

JavaScript Object Notation

+ +

JSON 是序列物件、陣列、數字、字串、布林值、還有 {{jsxref("null")}} 的語法。它建基、但不同於 JavaScript:有些 JavaScript 不是 JSON、而有些 JSON 不是 JavaScript。請參見 JSON: The JavaScript subset that isn't

+ + + + + + + + + + + + + + + + + + + + + + + +
JavaScript 與 JSON 的差別
JavaScript 型別與 JSON 的差別
物件與陣列屬性名稱必須是包含在雙引號中的字串;禁止尾後逗號。
數字數字不可以0作為開頭(在 JSON.stringify 0會被忽略,但是在 JSON.parse 會造成語法錯誤);小數點前面必須至少有一位數字。
字串 +

Only a limited set of characters may be escaped; certain control characters are prohibited; the Unicode line separator (U+2028) and paragraph separator (U+2029) characters are permitted; strings must be double-quoted. See the following example where {{jsxref("JSON.parse()")}} works fine and a {{jsxref("SyntaxError")}} is thrown when evaluating the code as JavaScript:

+ +
+var code = '"\u2028\u2029"';
+JSON.parse(code); // works fine
+eval(code); // fails
+
+
+ +

JSON 的完整語法如下:

+ +
JSON = null
+    or true or false
+    or JSONNumber
+    or JSONString
+    or JSONObject
+    or JSONArray
+
+JSONNumber = - PositiveNumber
+          or PositiveNumber
+PositiveNumber = DecimalNumber
+              or DecimalNumber . Digits
+              or DecimalNumber . Digits ExponentPart
+              or DecimalNumber ExponentPart
+DecimalNumber = 0
+             or OneToNine Digits
+ExponentPart = e Exponent
+            or E Exponent
+Exponent = Digits
+        or + Digits
+        or - Digits
+Digits = Digit
+      or Digits Digit
+Digit = 0 through 9
+OneToNine = 1 through 9
+
+JSONString = ""
+          or " StringCharacters "
+StringCharacters = StringCharacter
+                or StringCharacters StringCharacter
+StringCharacter = any character
+                  except " or \ or U+0000 through U+001F
+               or EscapeSequence
+EscapeSequence = \" or \/ or \\ or \b or \f or \n or \r or \t
+              or \u HexDigit HexDigit HexDigit HexDigit
+HexDigit = 0 through 9
+        or A through F
+        or a through f
+
+JSONObject = { }
+          or { Members }
+Members = JSONString : JSON
+       or Members , JSONString : JSON
+
+JSONArray = [ ]
+         or [ ArrayElements ]
+ArrayElements = JSON
+             or ArrayElements , JSON
+
+ +

Insignificant whitespace may be present anywhere except within a JSONNumber (numbers must contain no whitespace) or JSONString (where it is interpreted as the corresponding character in the string, or would cause an error). The tab character (U+0009), carriage return (U+000D), line feed (U+000A), and space (U+0020) characters are the only valid whitespace characters.

+ +

方法

+ +
+
{{jsxref("JSON.parse()")}}
+
解析 JSON 字串,能改變給定值和屬性、接著回傳解析值。
+
{{jsxref("JSON.stringify()")}}
+
回傳給定的 JSON 對應字串,可自行決定只想包括哪些特定屬性、或替換的屬性值。
+
+ +

Polyfill

+ +

舊版瀏覽器並不支援 JSON。你可以在程式碼開頭插入以下程式碼,以解決這個問題。這個程式碼能實做不支援原生 JSON 物件的瀏覽器(如 Internet Explorer 6)。

+ +

以下演算法能仿製原生 JSON 物件。

+ +
if (!window.JSON) {
+  window.JSON = {
+    parse: function(sJSON) { return eval('(' + sJSON + ')'); },
+    stringify: (function () {
+      var toString = Object.prototype.toString;
+      var hasOwnProperty = Object.prototype.hasOwnProperty;
+      var isArray = Array.isArray || function (a) { return toString.call(a) === '[object Array]'; };
+      var escMap = {'"': '\\"', '\\': '\\\\', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t'};
+      var escFunc = function (m) { return escMap[m] || '\\u' + (m.charCodeAt(0) + 0x10000).toString(16).substr(1); };
+      var escRE = /[\\"\u0000-\u001F\u2028\u2029]/g;
+      return function stringify(value) {
+        if (value == null) {
+          return 'null';
+        } else if (typeof value === 'number') {
+          return isFinite(value) ? value.toString() : 'null';
+        } else if (typeof value === 'boolean') {
+          return value.toString();
+        } else if (typeof value === 'object') {
+          if (typeof value.toJSON === 'function') {
+            return stringify(value.toJSON());
+          } else if (isArray(value)) {
+            var res = '[';
+            for (var i = 0; i < value.length; i++)
+              res += (i ? ', ' : '') + stringify(value[i]);
+            return res + ']';
+          } else if (toString.call(value) === '[object Object]') {
+            var tmp = [];
+            for (var k in value) {
+              // in case "hasOwnProperty" has been shadowed
+              if (hasOwnProperty.call(value, k))
+                tmp.push(stringify(k) + ': ' + stringify(value[k]));
+            }
+            return '{' + tmp.join(', ') + '}';
+          }
+        }
+        return '"' + value.toString().replace(escRE, escFunc) + '"';
+      };
+    })()
+  };
+}
+
+ +

More complex well-known polyfills for the JSON object are JSON2 and JSON3.

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.12', 'JSON')}}{{Spec2('ES5.1')}}Initial definition.
{{SpecName('ES6', '#sec-json-object', 'JSON')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-json-object', 'JSON')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ + + +
{{Compat("javascript.builtins.JSON")}}
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/json/parse/index.html b/files/zh-tw/web/javascript/reference/global_objects/json/parse/index.html new file mode 100644 index 0000000000..eb821587a5 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/json/parse/index.html @@ -0,0 +1,170 @@ +--- +title: JSON.parse() +slug: Web/JavaScript/Reference/Global_Objects/JSON/parse +translation_of: Web/JavaScript/Reference/Global_Objects/JSON/parse +--- +
{{JSRef}}
+ +

JSON.parse() 方法把會把一個JSON字串轉換成 JavaScript的數值或是物件。另外也可選擇使用reviver函數讓這些數值或是物件在被回傳之前做轉換。

+ +

語法

+ +
JSON.parse(text[, reviver])
+ +

參數

+ +
+
text
+
要解析成 JSON 的字串。針對 JSON 語法的描述,請參見 {{jsxref("JSON")}} 物件。
+
reviver {{optional_inline}}
+
為選擇性的參數,用來描述JSON字串中的值該如何被解析並回傳的函式(function)
+
+ +

回傳值

+ +

從給定的 JSON text 回傳對應的 {{jsxref("Object")}}。

+ +

Throws

+ +

如果解析的字串不是合法的JSON格式會丟出一個 {{jsxref("SyntaxError")}} 例外

+ +

範例

+ +

Using JSON.parse()

+ +
JSON.parse('{}');              // {}
+JSON.parse('true');            // true
+JSON.parse('"foo"');           // "foo"
+JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
+JSON.parse('null');            // null
+
+ +

使用 reviver 參數

+ +

如果reviver函數有被指定,字串解析後產生出來的值會在函式回傳前經過轉換。 具體來講,解析後的值或是物件屬性會一個接一個地被這個reviver函數過濾(順序是由巢狀架構中最深的到最淺的),而當一個屬性即將被過濾時,該屬性的名稱(字串形態)以及值會被當作參數傳入reviver函數。如果reviver函數回傳了 {{jsxref("undefined")}} (或是沒有回傳值, 例如:函式提早結束),則該屬性會從物件中被刪除;反之如果成功的話,該屬性的值就會被新的回傳值取代。

+ +

如果reviver只需轉換某些特定的值,請記得將其他不須特別轉換的值以原來的值回傳,否則這些值會從回傳的結果物件中刪除。

+ +
JSON.parse('{"p": 5}', function(k, v) {
+  if (typeof v === 'number') {
+    return v * 2;  // return v * 2 for numbers
+  }
+  return v;        // return everything else unchanged
+});
+
+// { p: 10 }
+
+JSON.parse('{"1": 1, "2": 2, "3": {"4": 4, "5": {"6": 6}}}', function(k, v) {
+  console.log(k); // log the current property name, the last is "".
+  return v;       // return the unchanged property value.
+});
+
+// 1
+// 2
+// 4
+// 6
+// 5
+// 3
+// ""
+
+ +

JSON.parse() 不容許尾部有逗號

+ +
// 這兩個都會拋出 SyntaxError
+JSON.parse('[1, 2, 3, 4, ]');
+JSON.parse('{"foo" : 1, }');
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態註解
{{SpecName('ES5.1', '#sec-15.12.2', 'JSON.parse')}}{{Spec2('ES5.1')}}初始定義。從 JavaScript 1.7 導入。
{{SpecName('ES6', '#sec-json.parse', 'JSON.parse')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-json.parse', 'JSON.parse')}}{{Spec2('ESDraft')}}
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
特徵ChromeFirefox (Gecko)Internet ExplorerOperaSafari
基本功能{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("8.0")}}{{CompatOpera("10.5")}}{{CompatSafari("4.0")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
特徵AndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本功能{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Gecko相關

+ +

從Gecko 29版本開始{{geckoRelease("29")}},錯誤格式的JSON字串會產生更詳細的錯誤訊息,包含造成解析錯誤的行數及列數。這在針對大量JSON資料進行除錯時會很有幫助。

+ +
JSON.parse('[1, 2, 3, 4,]');
+// SyntaxError: JSON.parse: unexpected character at
+// line 1 column 13 of the JSON data
+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/json/stringify/index.html b/files/zh-tw/web/javascript/reference/global_objects/json/stringify/index.html new file mode 100644 index 0000000000..5169d7d748 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/json/stringify/index.html @@ -0,0 +1,280 @@ +--- +title: JSON.stringify() +slug: Web/JavaScript/Reference/Global_Objects/JSON/stringify +translation_of: Web/JavaScript/Reference/Global_Objects/JSON/stringify +--- +
{{JSRef}}
+ +

JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.

+ +
{{EmbedInteractiveExample("pages/js/json-stringify.html")}}
+ +

語法

+ +
JSON.stringify(value[, replacer[, space]])
+ +

參數

+ +
+
value
+
The value to convert to a JSON string.
+
replacer {{optional_inline}}
+
A function that alters the behavior of the stringification process, or an array of {{jsxref("String")}} and {{jsxref("Number")}} objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string.
+
space {{optional_inline}}
+
A {{jsxref("String")}} or {{jsxref("Number")}} object that's used to insert white space into the output JSON string for readability purposes. If this is a Number, it indicates the number of space characters to use as white space; this number is capped at 10 (if it is greater, the value is just 10). Values less than 1 indicate that no space should be used. If this is a String, the string (or the first 10 characters of the string, if it's longer than that) is used as white space. If this parameter is not provided (or is null), no white space is used.
+
+ +

回傳值

+ +

A JSON string representing the given value.

+ +

Description

+ +

JSON.stringify() converts a value to JSON notation representing it:

+ + + +
JSON.stringify({});                  // '{}'
+JSON.stringify(true);                // 'true'
+JSON.stringify('foo');               // '"foo"'
+JSON.stringify([1, 'false', false]); // '[1,"false",false]'
+JSON.stringify({ x: 5 });            // '{"x":5}'
+
+JSON.stringify(new Date(2006, 0, 2, 15, 4, 5))
+// '"2006-01-02T15:04:05.000Z"'
+
+JSON.stringify({ x: 5, y: 6 });
+// '{"x":5,"y":6}'
+JSON.stringify([new Number(3), new String('false'), new Boolean(false)]);
+// '[3,"false",false]'
+
+JSON.stringify({ x: [10, undefined, function(){}, Symbol('')] });
+// '{"x":[10,null,null,null]}'
+
+// Symbols:
+JSON.stringify({ x: undefined, y: Object, z: Symbol('') });
+// '{}'
+JSON.stringify({ [Symbol('foo')]: 'foo' });
+// '{}'
+JSON.stringify({ [Symbol.for('foo')]: 'foo' }, [Symbol.for('foo')]);
+// '{}'
+JSON.stringify({ [Symbol.for('foo')]: 'foo' }, function(k, v) {
+  if (typeof k === 'symbol') {
+    return 'a symbol';
+  }
+});
+// '{}'
+
+// Non-enumerable properties:
+JSON.stringify( Object.create(null, { x: { value: 'x', enumerable: false }, y: { value: 'y', enumerable: true } }) );
+// '{"y":"y"}'
+
+
+ +

The replacer parameter

+ +

The replacer parameter can be either a function or an array. As a function, it takes two parameters, the key and the value being stringified. The object in which the key was found is provided as the replacer's this parameter. Initially it gets called with an empty key representing the object being stringified, and it then gets called for each property on the object or array being stringified. It should return the value that should be added to the JSON string, as follows:

+ + + +
Note: You cannot use the replacer function to remove values from an array. If you return undefined or a function then null is used instead.
+ +

Example with a function

+ +
function replacer(key, value) {
+  // Filtering out properties
+  if (typeof value === 'string') {
+    return undefined;
+  }
+  return value;
+}
+
+var foo = {foundation: 'Mozilla', model: 'box', week: 45, transport: 'car', month: 7};
+JSON.stringify(foo, replacer);
+// '{"week":45,"month":7}'
+
+ +

Example with an array

+ +

If replacer is an array, the array's values indicate the names of the properties in the object that should be included in the resulting JSON string.

+ +
JSON.stringify(foo, ['week', 'month']);
+// '{"week":45,"month":7}', only keep "week" and "month" properties
+
+ +

The space argument

+ +

The space argument may be used to control spacing in the final string. If it is a number, successive levels in the stringification will each be indented by this many space characters (up to 10). If it is a string, successive levels will be indented by this string (or the first ten characters of it).

+ +
JSON.stringify({ a: 2 }, null, ' ');
+// '{
+//  "a": 2
+// }'
+
+ +

Using a tab character mimics standard pretty-print appearance:

+ +
JSON.stringify({ uno: 1, dos: 2 }, null, '\t');
+// returns the string:
+// '{
+//     "uno": 1,
+//     "dos": 2
+// }'
+
+ +

toJSON() behavior

+ +

If an object being stringified has a property named toJSON whose value is a function, then the toJSON() method customizes JSON stringification behavior: instead of the object being serialized, the value returned by the toJSON() method when called will be serialized. JSON.stringify() calls toJSON with one parameter:

+ + + +

For example:

+ +
const bonnie = {
+  name: 'Bonnie Washington',
+  age: 17,
+  class: 'Year 5 Wisdom',
+  isMonitor: false,
+  toJSON: function(key) {
+    // Clone object to prevent accidentally performing modification on the original object
+    const cloneObj = { ...this };
+
+    delete cloneObj.age;
+    delete cloneObj.isMonitor;
+    cloneObj.year = 5;
+    cloneObj.class = 'Wisdom';
+
+    if (key) {
+      cloneObj.code = key;
+    }
+
+    return cloneObj;
+  }
+}
+
+JSON.stringify(bonnie);
+// Returns '{"name":"Bonnie Washington","class":"Wisdom","year":5}'
+
+const students = {bonnie};
+JSON.stringify(students);
+// Returns '{"bonnie":{"name":"Bonnie Washington","class":"Wisdom","year":5,"code":"bonnie"}}'
+
+const monitorCandidate = [bonnie];
+JSON.stringify(monitorCandidate)
+// Returns '[{"name":"Bonnie Washington","class":"Wisdom","year":5,"code":"0"}]'
+ +

Issue with plain JSON.stringify for use as JavaScript

+ +

Note that JSON is not a completely strict subset of JavaScript, with two line terminators (Line separator and Paragraph separator) not needing to be escaped in JSON but needing to be escaped in JavaScript. Therefore, if the JSON is meant to be evaluated or directly utilized within JSONP, the following utility can be used:

+ +
function jsFriendlyJSONStringify (s) {
+    return JSON.stringify(s).
+        replace(/\u2028/g, '\\u2028').
+        replace(/\u2029/g, '\\u2029');
+}
+
+var s = {
+    a: String.fromCharCode(0x2028),
+    b: String.fromCharCode(0x2029)
+};
+try {
+    eval('(' + JSON.stringify(s) + ')');
+} catch (e) {
+    console.log(e); // "SyntaxError: unterminated string literal"
+}
+
+// No need for a catch
+eval('(' + jsFriendlyJSONStringify(s) + ')');
+
+// console.log in Firefox unescapes the Unicode if
+//   logged to console, so we use alert
+alert(jsFriendlyJSONStringify(s)); // {"a":"\u2028","b":"\u2029"}
+ +

Example of using JSON.stringify() with localStorage

+ +

In a case where you want to store an object created by your user and allowing it to be restored even after the browser has been closed, the following example is a model for the applicability of JSON.stringify():

+ +
+

Functions are not a valid JSON data type so they will not work. However, they can be displayed if first converted to a string (e.g. in the replacer), via the function's toString method. Also, some objects like {{jsxref("Date")}} will be a string after {{jsxref("JSON.parse()")}}.

+
+ +
// Creating an example of JSON
+var session = {
+  'screens': [],
+  'state': true
+};
+session.screens.push({ 'name': 'screenA', 'width': 450, 'height': 250 });
+session.screens.push({ 'name': 'screenB', 'width': 650, 'height': 350 });
+session.screens.push({ 'name': 'screenC', 'width': 750, 'height': 120 });
+session.screens.push({ 'name': 'screenD', 'width': 250, 'height': 60 });
+session.screens.push({ 'name': 'screenE', 'width': 390, 'height': 120 });
+session.screens.push({ 'name': 'screenF', 'width': 1240, 'height': 650 });
+
+// Converting the JSON string with JSON.stringify()
+// then saving with localStorage in the name of session
+localStorage.setItem('session', JSON.stringify(session));
+
+// Example of how to transform the String generated through
+// JSON.stringify() and saved in localStorage in JSON object again
+var restoredSession = JSON.parse(localStorage.getItem('session'));
+
+// Now restoredSession variable contains the object that was saved
+// in localStorage
+console.log(restoredSession);
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.12.3', 'JSON.stringify')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.7.
{{SpecName('ES6', '#sec-json.stringify', 'JSON.stringify')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-json.stringify', 'JSON.stringify')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.JSON.stringify")}}

+
+ +

See also

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/map/index.html b/files/zh-tw/web/javascript/reference/global_objects/map/index.html new file mode 100644 index 0000000000..07dc862188 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/map/index.html @@ -0,0 +1,265 @@ +--- +title: Map +slug: Web/JavaScript/Reference/Global_Objects/Map +tags: + - ECMAScript 2015 + - JavaScript + - Map +translation_of: Web/JavaScript/Reference/Global_Objects/Map +--- +
{{JSRef}}
+ +

Map 是保存了鍵值對(key-value pairs)的物件。任何值(包括物件及{{Glossary("Primitive", "基本型別(primitive)值")}})都可以作為鍵或值。

+ +

語法

+ +
new Map([iterable])
+ +

參數

+ +
+
iterable
+
為一個{{jsxref("Array", "陣列")}}或其他元素成鍵值對的可迭代物件(有兩個元素的陣列,例如 [[ 1, 'one' ],[ 2, 'two' ]])。每一個鍵值對都會被加入至新的 Mapnull 會被視為 undefined
+
+ +

描述

+ +

一個 Map 物件會根據元素的新增順序走訪自身的所有元素 — {{jsxref("Statements/for...of", "for...of")}} 迴圈會在每次迭代回傳一個 [key, value] 陣列。

+ + + +

鍵的相等性

+ +

鍵相等是基於 SameValueZero 的演算法:NaN 被認為與 NaN 相同(即使 NaN !== NaN)並且根據 === 運算符的語義,所有其他值都被認為相等。在目前的ECMAScript 規範中,-0+0 被認為是相等的,儘管在早期的草案中並非如此。詳細的內容請參閱 {{anch("Browser compatibility")}} 表中的 "Value equality for -0 and 0"。

+ +

Object 及 Map 的比較

+ +

{{jsxref("Object")}} 和 Map 類似。兩者都允許你設置對應的鍵值對,檢索這些值,刪除鍵,並檢測是否有什麼存儲在鍵中。正因為如此(也因為沒有內置的替代品),Object 在歷史上一直被當作 Map 使用;然而在某些情況下,使用 Map 有一些重要的不同之處:

+ + + +

屬性

+ +
+
Map.length
+
length屬性的值為 0
+ 要計算 Map 中有多少元素,可以使用 {{jsxref("Map.prototype.size")}}。
+
{{jsxref("Map.@@species", "get Map[@@species]")}}
+
用於創建派生物件的構造函數。
+
{{jsxref("Map.prototype")}}
+
表示 Map 構造函數的原型,允許對所有的 Map 物件添加屬性
+
+ +

Map 物件實體

+ +

所有的 Map 實例都繼承自 {{jsxref("Map.prototype")}}.

+ +

屬性

+ +

{{page('zh-TW/Web/JavaScript/Reference/Global_Objects/Map/prototype','Properties')}}

+ +

方法

+ +

{{page('zh-TW/Web/JavaScript/Reference/Global_Objects/Map/prototype','Methods')}}

+ +

範例

+ +

使用 Map 物件

+ +
var myMap = new Map();
+
+var keyString = 'a string',
+    keyObj = {},
+    keyFunc = function() {};
+
+// setting the values
+myMap.set(keyString, "value associated with 'a string'");
+myMap.set(keyObj, 'value associated with keyObj');
+myMap.set(keyFunc, 'value associated with keyFunc');
+
+myMap.size; // 3
+
+// getting the values
+myMap.get(keyString);    // "value associated with 'a string'"
+myMap.get(keyObj);       // "value associated with keyObj"
+myMap.get(keyFunc);      // "value associated with keyFunc"
+
+myMap.get('a string');   // "value associated with 'a string'"
+                         // because keyString === 'a string'
+myMap.get({});           // undefined, because keyObj !== {}
+myMap.get(function() {}) // undefined, because keyFunc !== function () {}
+
+ +

使用 NaN 作為 Map 的鍵

+ +

NaN 同樣可以作為 Map 的 key,雖然每個 NaN 都不等於自己本身,下面的例子是有效的,因為 NaN 無法區分彼此。

+ +
var myMap = new Map();
+myMap.set(NaN, 'not a number');
+
+myMap.get(NaN); // "not a number"
+
+var otherNaN = Number('foo');
+myMap.get(otherNaN); // "not a number"
+
+ +

透過 for..of 迭代 Map

+ +

Map 可以使用 for..of 迴圈進行迭代:

+ +
var myMap = new Map();
+myMap.set(0, 'zero');
+myMap.set(1, 'one');
+for (var [key, value] of myMap) {
+  console.log(key + ' = ' + value);
+}
+// 0 = zero
+// 1 = one
+
+for (var key of myMap.keys()) {
+  console.log(key);
+}
+// 0
+// 1
+
+for (var value of myMap.values()) {
+  console.log(value);
+}
+// zero
+// one
+
+for (var [key, value] of myMap.entries()) {
+  console.log(key + ' = ' + value);
+}
+// 0 = zero
+// 1 = one
+
+ +

透過 forEach() 迭代 Map

+ +

Map 可以使用 forEach() 方法進行迭代:

+ +
myMap.forEach(function(value, key) {
+  console.log(key + ' = ' + value);
+});
+// Will show 2 logs; first with "0 = zero" and second with "1 = one"
+
+ +

與 Array 物件關聯

+ +
var kvArray = [['key1', 'value1'], ['key2', 'value2']];
+
+// Use the regular Map constructor to transform a 2D key-value Array into a map
+var myMap = new Map(kvArray);
+
+myMap.get('key1'); // returns "value1"
+
+// Use the Array.from function to transform a map into a 2D key-value Array
+console.log(Array.from(myMap)); // Will show you exactly the same Array as kvArray
+
+// Or use the keys or values iterators and convert them to an array
+console.log(Array.from(myMap.keys())); // Will show ["key1", "key2"]
+
+ + + +

 複製與合併 Map

+ +

就像 Array 一樣,Map 可以被複製:

+ +
var original = new Map([
+  [1, 'one']
+]);
+
+var clone = new Map(original);
+
+console.log(clone.get(1)); // one
+console.log(original === clone); // false. Useful for shallow comparison
+ +

請記住,數據本身並非克隆的。

+ +

Map 可以被合併,保持鍵的唯一性:

+ +
var first = new Map([
+  [1, 'one'],
+  [2, 'two'],
+  [3, 'three'],
+]);
+
+var second = new Map([
+  [1, 'uno'],
+  [2, 'dos']
+]);
+
+// Merge two maps. The last repeated key wins.
+// Spread operator essentially converts a Map to an Array
+var merged = new Map([...first, ...second]);
+
+console.log(merged.get(1)); // uno
+console.log(merged.get(2)); // dos
+console.log(merged.get(3)); // three
+ +

Map 也可以跟 Array 合併:

+ +
var first = new Map([
+  [1, 'one'],
+  [2, 'two'],
+  [3, 'three'],
+]);
+
+var second = new Map([
+  [1, 'uno'],
+  [2, 'dos']
+]);
+
+// Merge maps with an array. The last repeated key wins.
+var merged = new Map([...first, ...second, [1, 'eins']]);
+
+console.log(merged.get(1)); // eins
+console.log(merged.get(2)); // dos
+console.log(merged.get(3)); // three
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-map-objects', 'Map')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-map-objects', 'Map')}}{{Spec2('ESDraft')}}
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.Map")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/math/abs/index.html b/files/zh-tw/web/javascript/reference/global_objects/math/abs/index.html new file mode 100644 index 0000000000..91be97bc11 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/math/abs/index.html @@ -0,0 +1,104 @@ +--- +title: Math.abs() +slug: Web/JavaScript/Reference/Global_Objects/Math/abs +tags: + - JavaScript + - Math + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/abs +--- +
{{JSRef}}
+ +

Math.abs() 函式會回傳一個數字的絕對值,即為:

+ +

Math.abs(x)=|x|={xifx>00ifx=0-xifx<0{\mathtt{\operatorname{Math.abs}(x)}} = {|x|} = \begin{cases} x & \text{if} \quad x \geq 0 \\ x & \text{if} \quad x < 0 \end{cases}

+ +
{{EmbedInteractiveExample("pages/js/math-abs.html")}}
+ + + +

語法

+ +
Math.abs(x)
+ +

參數

+ +
+
x
+
一個數字。
+
+ +

回傳值

+ +

給定數字的絕對值。

+ +

描述

+ +

Because abs() is a static method of Math, you always use it as Math.abs(), rather than as a method of a Math object you created (Math is not a constructor).

+ +

範例

+ +

Math.abs() 的行為

+ +

Passing an empty object, an array with more than one member, a non-numeric string or {{jsxref("undefined")}}/empty variable returns {{jsxref("NaN")}}. Passing {{jsxref("null")}}, an empty string or an empty array returns 0.

+ +
Math.abs('-1');     // 1
+Math.abs(-2);       // 2
+Math.abs(null);     // 0
+Math.abs('');       // 0
+Math.abs([]);       // 0
+Math.abs([2]);      // 2
+Math.abs([1,2]);    // NaN
+Math.abs({});       // NaN
+Math.abs('string'); // NaN
+Math.abs();         // NaN
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.1', 'Math.abs')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.abs', 'Math.abs')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.abs', 'Math.abs')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.Math.abs")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/math/ceil/index.html b/files/zh-tw/web/javascript/reference/global_objects/math/ceil/index.html new file mode 100644 index 0000000000..7ce7174f0b --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/math/ceil/index.html @@ -0,0 +1,170 @@ +--- +title: Math.ceil() +slug: Web/JavaScript/Reference/Global_Objects/Math/ceil +tags: + - JavaScript + - Math + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/ceil +--- +
{{JSRef}}
+ +

Math.ceil() 函式會回傳大於等於所給數字的最小整數。

+ +
{{EmbedInteractiveExample("pages/js/math-ceil.html")}}
+ + + +

語法

+ +
Math.ceil(x)
+ +

參數

+ +
+
x
+
一個數字。
+
+ +

回傳值

+ +

一個大於等於指定數字的最小整數。

+ +

描述

+ +

Because ceil() is a static method of Math, you always use it as Math.ceil(), rather than as a method of a Math object you created (Math is not a constructor).

+ +

範例

+ +

使用 Math.ceil()

+ +

The following example shows example usage of Math.ceil().

+ +
Math.ceil(.95);    // 1
+Math.ceil(4);      // 4
+Math.ceil(7.004);  // 8
+Math.ceil(-0.95);  // -0
+Math.ceil(-4);     // -4
+Math.ceil(-7.004); // -7
+
+ +

Decimal adjustment

+ +
// Closure
+(function() {
+  /**
+   * Decimal adjustment of a number.
+   *
+   * @param {String}  type  The type of adjustment.
+   * @param {Number}  value The number.
+   * @param {Integer} exp   The exponent (the 10 logarithm of the adjustment base).
+   * @returns {Number} The adjusted value.
+   */
+  function decimalAdjust(type, value, exp) {
+    // If the exp is undefined or zero...
+    if (typeof exp === 'undefined' || +exp === 0) {
+      return Math[type](value);
+    }
+    value = +value;
+    exp = +exp;
+    // If the value is not a number or the exp is not an integer...
+    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
+      return NaN;
+    }
+    // Shift
+    value = value.toString().split('e');
+    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
+    // Shift back
+    value = value.toString().split('e');
+    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
+  }
+
+  // Decimal round
+  if (!Math.round10) {
+    Math.round10 = function(value, exp) {
+      return decimalAdjust('round', value, exp);
+    };
+  }
+  // Decimal floor
+  if (!Math.floor10) {
+    Math.floor10 = function(value, exp) {
+      return decimalAdjust('floor', value, exp);
+    };
+  }
+  // Decimal ceil
+  if (!Math.ceil10) {
+    Math.ceil10 = function(value, exp) {
+      return decimalAdjust('ceil', value, exp);
+    };
+  }
+})();
+
+// Round
+Math.round10(55.55, -1);   // 55.6
+Math.round10(55.549, -1);  // 55.5
+Math.round10(55, 1);       // 60
+Math.round10(54.9, 1);     // 50
+Math.round10(-55.55, -1);  // -55.5
+Math.round10(-55.551, -1); // -55.6
+Math.round10(-55, 1);      // -50
+Math.round10(-55.1, 1);    // -60
+// Floor
+Math.floor10(55.59, -1);   // 55.5
+Math.floor10(59, 1);       // 50
+Math.floor10(-55.51, -1);  // -55.6
+Math.floor10(-51, 1);      // -60
+// Ceil
+Math.ceil10(55.51, -1);    // 55.6
+Math.ceil10(51, 1);        // 60
+Math.ceil10(-55.59, -1);   // -55.5
+Math.ceil10(-59, 1);       // -50
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.6', 'Math.ceil')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.ceil', 'Math.ceil')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.ceil', 'Math.ceil')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.Math.ceil")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/math/floor/index.html b/files/zh-tw/web/javascript/reference/global_objects/math/floor/index.html new file mode 100644 index 0000000000..5587d60838 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/math/floor/index.html @@ -0,0 +1,169 @@ +--- +title: Math.floor() +slug: Web/JavaScript/Reference/Global_Objects/Math/floor +tags: + - JavaScript + - Math + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/floor +--- +
{{JSRef}}
+ +

Math.floor() 函式會回傳小於等於所給數字的最大整數。

+ +
{{EmbedInteractiveExample("pages/js/math-floor.html")}}
+ + + +

語法

+ +
Math.floor(x)
+ +

參數

+ +
+
x
+
數字型態。
+
+ +

回傳值

+ +

小於等於所給數字的最大整數。

+ +

描述

+ +

 floor() 是 Math的靜態函式, 所以不需實體化Math 物件, 只要直接呼叫 Math.floor()就能使用。

+ +

(此外Math 並不是建構子).

+ +

範例

+ +

使用 Math.floor()

+ +
Math.floor( 45.95); //  45
+Math.floor( 45.05); //  45
+Math.floor(  4   ); //   4
+Math.floor(-45.05); // -46
+Math.floor(-45.95); // -46
+
+ +

Decimal adjustment

+ +
// Closure
+(function() {
+  /**
+   * Decimal adjustment of a number.
+   *
+   * @param {String}  type  The type of adjustment.
+   * @param {Number}  value The number.
+   * @param {Integer} exp   The exponent (the 10 logarithm of the adjustment base).
+   * @returns {Number} The adjusted value.
+   */
+  function decimalAdjust(type, value, exp) {
+    // If the exp is undefined or zero...
+    if (typeof exp === 'undefined' || +exp === 0) {
+      return Math[type](value);
+    }
+    value = +value;
+    exp = +exp;
+    // If the value is not a number or the exp is not an integer...
+    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
+      return NaN;
+    }
+    // Shift
+    value = value.toString().split('e');
+    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
+    // Shift back
+    value = value.toString().split('e');
+    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
+  }
+
+  // Decimal round
+  if (!Math.round10) {
+    Math.round10 = function(value, exp) {
+      return decimalAdjust('round', value, exp);
+    };
+  }
+  // Decimal floor
+  if (!Math.floor10) {
+    Math.floor10 = function(value, exp) {
+      return decimalAdjust('floor', value, exp);
+    };
+  }
+  // Decimal ceil
+  if (!Math.ceil10) {
+    Math.ceil10 = function(value, exp) {
+      return decimalAdjust('ceil', value, exp);
+    };
+  }
+})();
+
+// Round
+Math.round10(55.55, -1);   // 55.6
+Math.round10(55.549, -1);  // 55.5
+Math.round10(55, 1);       // 60
+Math.round10(54.9, 1);     // 50
+Math.round10(-55.55, -1);  // -55.5
+Math.round10(-55.551, -1); // -55.6
+Math.round10(-55, 1);      // -50
+Math.round10(-55.1, 1);    // -60
+// Floor
+Math.floor10(55.59, -1);   // 55.5
+Math.floor10(59, 1);       // 50
+Math.floor10(-55.51, -1);  // -55.6
+Math.floor10(-51, 1);      // -60
+// Ceil
+Math.ceil10(55.51, -1);    // 55.6
+Math.ceil10(51, 1);        // 60
+Math.ceil10(-55.59, -1);   // -55.5
+Math.ceil10(-59, 1);       // -50
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.9', 'Math.floor')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-math.floor', 'Math.floor')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-math.floor', 'Math.floor')}}{{Spec2('ESDraft')}}
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.Math.floor")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/math/index.html b/files/zh-tw/web/javascript/reference/global_objects/math/index.html new file mode 100644 index 0000000000..c67999150e --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/math/index.html @@ -0,0 +1,196 @@ +--- +title: Math +slug: Web/JavaScript/Reference/Global_Objects/Math +tags: + - JavaScript + - Math + - NeedsTranslation + - Reference + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Math +--- +
{{JSRef}}
+ +

Math 是一個擁有數學常數及數學函數(非函式物件)屬性及方法的內建物件。

+ +

描述

+ +

不像其他的全域物件,Math 並非建構函式。所有 Math 的屬性及方法皆為靜態。你可以使用 Math.PI 來參考到圓周率 pi 的常數值,以及可以呼叫 Math.sin(x) 函式來計算三角函數正弦曲線 sine(x 為方法的引數)。常數是由 JavaScript 中實數的完整精度來定義。

+ +

屬性

+ +
+
{{jsxref("Math.E")}}
+
歐拉常數 (此指自然常數) ,也是自然對數的底數,約為2.718。
+
{{jsxref("Math.LN2")}}
+
2 的自然對數,約為0.693。
+
{{jsxref("Math.LN10")}}
+
10 的自然對數,約為2.303。
+
{{jsxref("Math.LOG2E")}}
+
以 2 為底的 E 的對數,約為1.443。
+
{{jsxref("Math.LOG10E")}}
+
以 10 為底的 E 的對數,約為0.434。
+
{{jsxref("Math.PI")}}
+
一個圓的圓周和其直徑比值,約為 3.14159。
+
{{jsxref("Math.SQRT1_2")}}
+
1/2的平方根;也就是1除以2的平方根,約為 0.707。
+
{{jsxref("Math.SQRT2")}}
+
2的平方根,約為 1.414。
+
+ +

方法

+ +
+

注意三角函數 (sin(), cos(), tan(), asin(), acos(), atan(), atan2()) 的參數或回傳值的角度皆以弧度為單位。把角度乘上 (Math.PI / 180) 會得到弧度單位,將弧度除以該數則會轉換回一般所用的角度單位。

+
+ +
+

注意許多數學方法的精度是取決於實作方式的。這意味著不同的瀏覽器可能會得到不同的結果,甚至同一個 JS引擎在不同的作業系統或架構上所得到的結果都有可能相異。

+
+ +
+
{{jsxref("Global_Objects/Math/abs", "Math.abs(x)")}}
+
回傳 x 的絕對值。
+
{{jsxref("Global_Objects/Math/acos", "Math.acos(x)")}}
+
回傳 x 的反餘弦值。
+
{{jsxref("Global_Objects/Math/acosh", "Math.acosh(x)")}}
+
Returns the hyperbolic arccosine of a number.
+
{{jsxref("Global_Objects/Math/asin", "Math.asin(x)")}}
+
回傳 x 的反正弦值。
+
{{jsxref("Global_Objects/Math/asinh", "Math.asinh(x)")}}
+
Returns the hyperbolic arcsine of a number.
+
{{jsxref("Global_Objects/Math/atan", "Math.atan(x)")}}
+
回傳 x 的反正切值。
+
{{jsxref("Global_Objects/Math/atanh", "Math.atanh(x)")}}
+
Returns the hyperbolic arctangent of a number.
+
{{jsxref("Global_Objects/Math/atan2", "Math.atan2(y, x)")}}
+
Returns the arctangent of the quotient of its arguments.
+
{{jsxref("Global_Objects/Math/cbrt", "Math.cbrt(x)")}}
+
回傳 x 的立方根值。
+
{{jsxref("Global_Objects/Math/ceil", "Math.ceil(x)")}}
+
回傳不小於 x 的最小整數值。
+
{{jsxref("Global_Objects/Math/clz32", "Math.clz32(x)")}}
+
Returns the number of leading zeroes of a 32-bit integer.
+
{{jsxref("Global_Objects/Math/cos", "Math.cos(x)")}}
+
回傳 x 的餘弦值。
+
{{jsxref("Global_Objects/Math/cosh", "Math.cosh(x)")}}
+
Returns the hyperbolic cosine of a number.
+
{{jsxref("Global_Objects/Math/exp", "Math.exp(x)")}}
+
回傳 Ex,x 為給定數值,E 為歐拉常數 (自然對數的底數)。
+
{{jsxref("Global_Objects/Math/expm1", "Math.expm1(x)")}}
+
回傳 exp(x) 減去1的值。
+
{{jsxref("Global_Objects/Math/floor", "Math.floor(x)")}}
+
回傳不大於 x 的最大整數值。
+
{{jsxref("Global_Objects/Math/fround", "Math.fround(x)")}}
+
Returns the nearest single precision float representation of a number.
+
{{jsxref("Global_Objects/Math/hypot", "Math.hypot([x[, y[, …]]])")}}
+
回傳參數平方之和的平方根。
+
{{jsxref("Global_Objects/Math/imul", "Math.imul(x, y)")}}
+
Returns the result of a 32-bit integer multiplication.
+
{{jsxref("Global_Objects/Math/log", "Math.log(x)")}}
+
回傳 x 的自然對數值。
+
{{jsxref("Global_Objects/Math/log1p", "Math.log1p(x)")}}
+
回傳 1 + x 的自然對數值。
+
{{jsxref("Global_Objects/Math/log10", "Math.log10(x)")}}
+
回傳以 10 為底,x 的對數值。
+
{{jsxref("Global_Objects/Math/log2", "Math.log2(x)")}}
+
回傳以 2 為底,x 的對數值。
+
{{jsxref("Global_Objects/Math/max", "Math.max([x[, y[, …]]])")}}
+
回傳給定數值中的最大值。
+
{{jsxref("Global_Objects/Math/min", "Math.min([x[, y[, …]]])")}}
+
回傳給定數值中的最小值。
+
{{jsxref("Global_Objects/Math/pow", "Math.pow(x, y)")}}
+
回傳 x 的 y 次方,也就是 xy
+
{{jsxref("Global_Objects/Math/random", "Math.random()")}}
+
回傳一個 0 到 1 之間的偽隨機值。
+
{{jsxref("Global_Objects/Math/round", "Math.round(x)")}}
+
回傳 x 的四捨五入值。
+
{{jsxref("Global_Objects/Math/sign", "Math.sign(x)")}}
+
回傳 x 的正負號,也就是回傳 x 的正負。
+
{{jsxref("Global_Objects/Math/sin", "Math.sin(x)")}}
+
回傳 x 的正弦值。
+
{{jsxref("Global_Objects/Math/sinh", "Math.sinh(x)")}}
+
Returns the hyperbolic sine of a number.
+
{{jsxref("Global_Objects/Math/sqrt", "Math.sqrt(x)")}}
+
回傳 x 的正平方根。
+
{{jsxref("Global_Objects/Math/tan", "Math.tan(x)")}}
+
回傳 x 的正切值。
+
{{jsxref("Global_Objects/Math/tanh", "Math.tanh(x)")}}
+
Returns the hyperbolic tangent of a number.
+
Math.toSource() {{non-standard_inline}}
+
回傳字串 "Math"
+
{{jsxref("Global_Objects/Math/trunc", "Math.trunc(x)")}}
+
Returns the integral part of the number x, removing any fractional digits.
+
+ +

擴充 Math 物件

+ +

As most of the built-in objects in JavaScript, the Math object can be extended with custom properties and methods. To extend the Math object, you do not use 'prototype'. Instead, you directly extend Math:

+ +
Math.propName = propValue;
+Math.methodName = methodRef;
+ +

For instance, the following example adds a method to the Math object for calculating the greatest common divisor of a list of arguments.

+ +
/* Variadic function -- Returns the greatest common divisor of a list of arguments */
+Math.gcd = function() {
+    if (arguments.length == 2) {
+        if (arguments[1] == 0)
+            return arguments[0];
+        else
+            return Math.gcd(arguments[1], arguments[0] % arguments[1]);
+    } else if (arguments.length > 2) {
+        var result = Math.gcd(arguments[0], arguments[1]);
+        for (var i = 2; i < arguments.length; i++)
+            result = Math.gcd(result, arguments[i]);
+        return result;
+    }
+};
+ +

Try it:

+ +
console.log(Math.gcd(20, 30, 15, 70, 40)); // `5`
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.8', 'Math')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math-object', 'Math')}}{{Spec2('ES6')}}New methods {{jsxref("Math.log10()", "log10()")}}, {{jsxref("Math.log2()", "log2()")}}, {{jsxref("Math.log1p()", "log1p()")}}, {{jsxref("Math.expm1()", "expm1()")}}, {{jsxref("Math.cosh()", "cosh()")}}, {{jsxref("Math.sinh()", "sinh()")}}, {{jsxref("Math.tanh()", "tanh()")}}, {{jsxref("Math.acosh()", "acosh()")}}, {{jsxref("Math.asinh()", "asinh()")}}, {{jsxref("Math.atanh()", "atanh()")}}, {{jsxref("Math.hypot()", "hypot()")}}, {{jsxref("Math.trunc()", "trunc()")}}, {{jsxref("Math.sign()", "sign()")}}, {{jsxref("Math.imul()", "imul()")}}, {{jsxref("Math.fround()", "fround()")}}, {{jsxref("Math.cbrt()", "cbrt()")}} and {{jsxref("Math.clz32()", "clz32()")}} added.
{{SpecName('ESDraft', '#sec-math-object', 'Math')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.Math")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/math/max/index.html b/files/zh-tw/web/javascript/reference/global_objects/math/max/index.html new file mode 100644 index 0000000000..1f53898090 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/math/max/index.html @@ -0,0 +1,117 @@ +--- +title: Math.max() +slug: Web/JavaScript/Reference/Global_Objects/Math/max +tags: + - JavaScript + - Math + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/max +--- +
{{JSRef}}
+ +

Math.max() 函式會回傳零或多個數字中的最大值。

+ +
{{EmbedInteractiveExample("pages/js/math-max.html")}}
+ + + +

語法

+ +
Math.max([value1[, value2[, ...]]])
+ +

Parameters

+ +
+
value1, value2, ...
+
Numbers.
+
+ +

Return value

+ +

The largest of the given numbers. If at least one of the arguments cannot be converted to a number, {{jsxref("NaN")}} is returned.

+ +

說明

+ +

Because max() is a static method of Math, you always use it as Math.max(), rather than as a method of a Math object you created (Math is not a constructor).

+ +

If no arguments are given, the result is -{{jsxref("Infinity")}}.

+ +

If at least one of arguments cannot be converted to a number, the result is {{jsxref("NaN")}}.

+ +

範例

+ +

Using Math.max()

+ +
Math.max(10, 20);   //  20
+Math.max(-10, -20); // -10
+Math.max(-10, 20);  //  20
+
+ +

Getting the maximum element of an array

+ +

{{jsxref("Array.prototype.reduce", "Array.reduce()")}} can be used to find the maximum element in a numeric array, by comparing each value:

+ +
var arr = [1,2,3];
+var max = arr.reduce(function(a, b) {
+    return Math.max(a, b);
+});
+
+ +

The following function uses {{jsxref("Function.prototype.apply()")}} to get the maximum of an array. getMaxOfArray([1, 2, 3]) is equivalent to Math.max(1, 2, 3), but you can use getMaxOfArray() on programmatically constructed arrays. This should only be used for arrays with relatively few elements.

+ +
function getMaxOfArray(numArray) {
+  return Math.max.apply(null, numArray);
+}
+ +

The new spread operator is a shorter way of writing the apply solution to get the maximum of an array:

+ +
var arr = [1, 2, 3];
+var max = Math.max(...arr);
+
+ +

However, both spread (...) and apply will either fail or return the wrong result if the array has too many elements, because they try to pass the array elements as function parameters. See Using apply and built-in functions for more details. The reduce solution does not have this problem.

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.11', 'Math.max')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.max', 'Math.max')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.max', 'Math.max')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.Math.max")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/math/pow/index.html b/files/zh-tw/web/javascript/reference/global_objects/math/pow/index.html new file mode 100644 index 0000000000..00ccb041ae --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/math/pow/index.html @@ -0,0 +1,107 @@ +--- +title: Math.pow() +slug: Web/JavaScript/Reference/Global_Objects/Math/pow +tags: + - 次方 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/pow +--- +
{{JSRef}}
+ +

Math.pow() 函式回傳 baseexponent 次方(幂)值,也就是 baseexponent

+ +

語法

+ +
Math.pow(base, exponent)
+ +

參數

+ +
+
base
+
基數。
+
exponent
+
要乘上 base 幾次的指數。
+
+ +

回傳值

+ +

A number representing the given base taken to the power of the given exponent.

+ +

敘述

+ +

The Math.pow() function returns the base to the exponent power, that is, baseexponent, the base and the exponent are in decimal numeral system.

+ +

由於 pow()Math 的靜態方法,you always use it as Math.pow(), rather than as a method of a Math object you created(Math 並沒有建構子)。

+ +

示例

+ +

使用 Math.pow()

+ +
// simple
+Math.pow(7, 2);    // 49
+Math.pow(7, 3);    // 343
+Math.pow(2, 10);   // 1024
+// fractional exponents
+Math.pow(4, 0.5);  // 2 (4 的平方根)
+Math.pow(8, 1/3);  // 2 (8 的立方根)
+Math.pow(2, 0.5);  // 1.4142135623730951 (2 的平方根)
+Math.pow(2, 1/3);  // 1.2599210498948732 (2 的立方根)
+// signed exponents
+Math.pow(7, -2);   // 0.02040816326530612 (1/49)
+Math.pow(8, -1/3); // 0.5
+// signed bases
+Math.pow(-7, 2);   // 49 (負負得正,2次方都是正數)
+Math.pow(-7, 3);   // -343 (3次方有可能為負數)
+Math.pow(-7, 0.5); // NaN (負數沒辦法得出一個實數平方根)
+// due to "even" and "odd" roots laying close to each other,
+// and limits in the floating number precision,
+// negative bases with fractional exponents always return NaN
+Math.pow(-7, 1/3); // NaN
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態註解
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.13', 'Math.pow')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-math.pow', 'Math.pow')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-math.pow', 'Math.pow')}}{{Spec2('ESDraft')}}
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.Math.pow")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/math/random/index.html b/files/zh-tw/web/javascript/reference/global_objects/math/random/index.html new file mode 100644 index 0000000000..4f7b65f844 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/math/random/index.html @@ -0,0 +1,95 @@ +--- +title: Math.random() +slug: Web/JavaScript/Reference/Global_Objects/Math/random +tags: + - 浮點數 + - 隨機 +translation_of: Web/JavaScript/Reference/Global_Objects/Math/random +--- +
{{JSRef}}
+ +

函數 Math.random() 會回傳一個偽隨機小數 (pseudo-random) 介於0到1之間(包含 0,不包含1) ,大致符合數學與統計上的均勻分佈 (uniform distribution) ,您可以選定想要的數字區間,它會透過演算法被產生並且不允許使用者自行跳選或重設成特定數字。{{EmbedInteractiveExample("pages/js/math-random.html")}}

+ +
+

Math.random() 所產生的偽隨機小數不符合加密學安全性要求。請勿使用於任何加密、資安相關領域。

+ +

如有加密需求建議參考Web Crypto APIwindow.crypto.getRandomValues()

+
+ +

語法

+ +
Math.random()
+ +

回傳值 Return value

+ +

回傳一個偽隨機小數 (pseudo-random),小數也稱浮點數; 介於0到1之間(包含 0,不包含1) 。

+ +

範例

+ +

請留意JavaScript中的數字與許多語言一樣使用 IEEE 754 floating point numbers with round-to-nearest-even behavior, the ranges claimed for the functions below (excluding the one for Math.random() itself) aren't exact. If extremely large bounds are chosen (253 or higher), it's possible in extremely rare cases to calculate the usually-excluded upper bound.

+ +

Getting a random number between 0 (inclusive) and 1 (exclusive)

+ +
function getRandom() {
+  return Math.random();
+}
+
+ +

Getting a random number between two values

+ +

This example returns a random number between the specified values. The returned value is no lower than (and may possibly equal) min, and is less than (and not equal) max.

+ +
function getRandomArbitrary(min, max) {
+  return Math.random() * (max - min) + min;
+}
+
+ +

Getting a random integer between two values

+ +

This example returns a random integer between the specified values. The value is no lower than min (or the next integer greater than min if min isn't an integer), and is less than (but not equal to) max.

+ +
function getRandomInt(min, max) {
+  min = Math.ceil(min);
+  max = Math.floor(max);
+  return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
+}
+
+ +
+

It might be tempting to use Math.round() to accomplish that, but doing so would cause your random numbers to follow a non-uniform distribution, which may not be acceptable for your needs.

+
+ +

Getting a random integer between two values, inclusive

+ +

While the getRandomInt() function above is inclusive at the minimum, it's exclusive at the maximum. What if you need the results to be inclusive at both the minimum and the maximum? The getRandomIntInclusive() function below accomplishes that.

+ +
function getRandomIntInclusive(min, max) {
+  min = Math.ceil(min);
+  max = Math.floor(max);
+  return Math.floor(Math.random() * (max - min + 1) + min); //The maximum is inclusive and the minimum is inclusive
+}
+ +

Specifications

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-math.random', 'Math.random')}}
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.Math.random")}}

+ +

其他參考資料

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/math/round/index.html b/files/zh-tw/web/javascript/reference/global_objects/math/round/index.html new file mode 100644 index 0000000000..5e6a0ea694 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/math/round/index.html @@ -0,0 +1,212 @@ +--- +title: Math.round() +slug: Web/JavaScript/Reference/Global_Objects/Math/round +tags: + - JavaScript + - Math + - Method + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Math/round +--- +
{{JSRef}}
+ +

Math.round() 函數回傳四捨五入後的近似值.

+ +

表達式

+ +
Math.round(x)
+ +

參數

+ +
+
x
+
數字.
+
+ +

描述

+ +

如果小數位的部分值大於 0.5, 這個值將會進位. 如果小數位的部分值小於 0.5, 這個值將不會進位.

+ +

由於 round() 是靜態的方法, 所以總是得這樣使用 Math.round(), 而非作為 Math 物件的一個方法 (Math並沒有建構子).

+ +

範例

+ +

使用 Math.round()

+ +
// Returns the value 20
+x = Math.round(20.49);
+
+// Returns the value 21
+x = Math.round(20.5);
+
+// Returns the value -20
+x = Math.round(-20.5);
+
+// Returns the value -21
+x = Math.round(-20.51);
+
+// Returns the value 1 (!)
+// Note the rounding error because of inaccurate floating point arithmetics
+// Compare this with Math.round10(1.005, -2) from the example below
+x = Math.round(1.005*100)/100;
+
+ +

十進位近似值

+ +
// 閉包含數
+(function() {
+  /**
+   * Decimal adjustment of a number.
+   *
+   * @param {String}  type  The type of adjustment.
+   * @param {Number}  value The number.
+   * @param {Integer} exp   The exponent (the 10 logarithm of the adjustment base).
+   * @returns {Number} The adjusted value.
+   */
+  function decimalAdjust(type, value, exp) {
+    // If the exp is undefined or zero...
+    if (typeof exp === 'undefined' || +exp === 0) {
+      return Math[type](value);
+    }
+    value = +value;
+    exp = +exp;
+    // If the value is not a number or the exp is not an integer...
+    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
+      return NaN;
+    }
+    // Shift
+    value = value.toString().split('e');
+    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
+    // Shift back
+    value = value.toString().split('e');
+    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
+  }
+
+  // Decimal round
+  if (!Math.round10) {
+    Math.round10 = function(value, exp) {
+      return decimalAdjust('round', value, exp);
+    };
+  }
+  // Decimal floor
+  if (!Math.floor10) {
+    Math.floor10 = function(value, exp) {
+      return decimalAdjust('floor', value, exp);
+    };
+  }
+  // Decimal ceil
+  if (!Math.ceil10) {
+    Math.ceil10 = function(value, exp) {
+      return decimalAdjust('ceil', value, exp);
+    };
+  }
+})();
+
+// Round
+Math.round10(55.55, -1);   // 55.6
+Math.round10(55.549, -1);  // 55.5
+Math.round10(55, 1);       // 60
+Math.round10(54.9, 1);     // 50
+Math.round10(-55.55, -1);  // -55.5
+Math.round10(-55.551, -1); // -55.6
+Math.round10(-55, 1);      // -50
+Math.round10(-55.1, 1);    // -60
+Math.round10(1.005, -2);   // 1.01 -- compare this with Math.round(1.005*100)/100 above
+// Floor
+Math.floor10(55.59, -1);   // 55.5
+Math.floor10(59, 1);       // 50
+Math.floor10(-55.51, -1);  // -55.6
+Math.floor10(-51, 1);      // -60
+// Ceil
+Math.ceil10(55.51, -1);    // 55.6
+Math.ceil10(51, 1);        // 60
+Math.ceil10(-55.59, -1);   // -55.5
+Math.ceil10(-59, 1);       // -50
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.15', 'Math.round')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.round', 'Math.round')}}{{Spec2('ES6')}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/nan/index.html b/files/zh-tw/web/javascript/reference/global_objects/nan/index.html new file mode 100644 index 0000000000..ef027d387f --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/nan/index.html @@ -0,0 +1,85 @@ +--- +title: NaN +slug: Web/JavaScript/Reference/Global_Objects/NaN +translation_of: Web/JavaScript/Reference/Global_Objects/NaN +--- +
{{jsSidebar("Objects")}}
+ +

全域屬性 NaN 表示「非數值」(Not-A-Number)的數值。

+ +

{{js_property_attributes(0,0,0)}}

+ +
{{EmbedInteractiveExample("pages/js/globalprops-nan.html")}}
+ +

語法

+ +
NaN
+ +

描述

+ +

NaN 的屬性屬於全域物件

+ +

如同 {{jsxref("Number.NaN")}} 一般,NaN 的初始數值是「非數值」。在當今的瀏覽器中,NaN 屬性不可設定(non-configurable)也不可覆寫(non-writable)。雖然可能有例外,也請不要覆蓋它。

+ +

寫程式很少會直接動用 NaN。通常是在 {{jsxref("Math")}} 函式計算失敗(Math.sqrt(-1))或函式解析數字失敗(parseInt("blabla"))後才會回傳。

+ +

偵測是否為 NaN

+ +

NaN 不等於(==!====!==)任何值,包括 NaN 本身。請使用 {{jsxref("Number.isNaN()")}} 或 {{jsxref("Global_Objects/isNaN", "isNaN()")}} 來確認某個數值是否為 NaN。Or perform a self-comparison: NaN, and only NaN, will compare unequal to itself.

+ +
NaN === NaN;        // false
+Number.NaN === NaN; // false
+isNaN(NaN);         // true
+isNaN(Number.NaN);  // true
+
+function valueIsNaN(v) { return v !== v; }
+valueIsNaN(1);          // false
+valueIsNaN(NaN);        // true
+valueIsNaN(Number.NaN); // true
+
+ +

但請注意 isNaN()Number.isNaN() 之間是有區別的:前者會在目前數字是 NaN 的時候回傳 true,或在裡面包藏一個號碼後變成 NaN;而後者,只有在數值是 NaN 的時候才會回傳 true

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態註解
{{SpecName('ES1')}}{{Spec2('ES1')}}初始定義。JavaScript 1.3 導入
{{SpecName('ES5.1', '#sec-15.1.1.1', 'NaN')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-value-properties-of-the-global-object-nan', 'NaN')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-value-properties-of-the-global-object-nan', 'NaN')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +

{{Compat("javascript.builtins.NaN")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/null/index.html b/files/zh-tw/web/javascript/reference/global_objects/null/index.html new file mode 100644 index 0000000000..0af88facab --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/null/index.html @@ -0,0 +1,124 @@ +--- +title: 'null' +slug: Web/JavaScript/Reference/Global_Objects/null +translation_of: Web/JavaScript/Reference/Global_Objects/null +--- +
{{jsSidebar("Objects")}}
+ +

The value null represents the intentional absence of any object value. It is one of JavaScript's {{Glossary("Primitive", "primitive values")}}.

+ +

語法

+ +
null 
+ +

描述

+ +

The value null is written with a literal, null (it's not an identifer for a property of the global object like {{jsxref("Global_Objects/undefined","undefined")}} can be). In APIs, null is often retrieved in place where an object can be expected but no object is relevant. When checking for null or undefined beware of the differences between equality (==) and identity (===) operators (type-conversion is performed with the former).

+ +
// foo does not exist. It is not defined and has never been initialized:
+> foo
+"ReferenceError: foo is not defined"
+
+// foo is known to exist now but it has no type or value:
+> var foo = null; foo
+"null"
+
+ +

Difference between null and undefined

+ +
typeof null        // object (bug in ECMAScript, should be null)
+typeof undefined   // undefined
+null === undefined // false
+null  == undefined // true
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-4.3.11', 'null value')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-null-value', 'null value')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-null-value', 'null value')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/number/index.html b/files/zh-tw/web/javascript/reference/global_objects/number/index.html new file mode 100644 index 0000000000..8a023d1603 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/number/index.html @@ -0,0 +1,219 @@ +--- +title: Number +slug: Web/JavaScript/Reference/Global_Objects/Number +tags: + - JavaScript + - NeedsTranslation + - Number + - Reference + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Number +--- +
{{JSRef}}
+ +

Number JavaScript 物件是允許你操作數值的包覆物件. Number 物件是以 Number() 建構子來建立的。

+ +

語法

+ +
new Number(value);
+ +

參數

+ +
+
value
+
用來建立物件的數值。
+
+ +

說明

+ +

Number 物件主要的用途:

+ + + +

屬性

+ +
+
{{jsxref("Number.EPSILON")}}
+
介於1和大於1的最小值之可表示的差。
+
{{jsxref("Number.MAX_SAFE_INTEGER")}}
+
JavaScript 中 IEEE-754 雙精度範圍間的最大整數 (253 - 1) 。
+
{{jsxref("Number.MAX_VALUE")}}
+
可表示的最大正整數。
+
{{jsxref("Number.MIN_SAFE_INTEGER")}}
+
JavaScript 中 IEEE-754 雙精度範圍間的最小整數 (-(253 - 1)) 。
+
{{jsxref("Number.MIN_VALUE")}}
+
可表示的最小值,即最靠近0的正整數?(5.00×103245.00\times10^{324})。
+
{{jsxref("Number.NaN")}}
+
特別用來表示非數值的物件。
+
{{jsxref("Number.NEGATIVE_INFINITY")}}
+
特別用來表示負無窮的數值。
+
{{jsxref("Number.POSITIVE_INFINITY")}}
+
特別用來表示正無窮的數值。
+
{{jsxref("Number.prototype")}}
+
允許被添加到 Number 物件的屬性。
+
+ +

方法

+ +
+
{{jsxref("Number.isNaN()")}}
+
判斷傳入的值是不是 NaN.
+
{{jsxref("Number.isFinite()")}}
+
判斷傳入的值是不是一個有限的數值。
+
{{jsxref("Number.isInteger()")}}
+
判斷傳入的值是不是一個整數。
+
{{jsxref("Number.isSafeInteger()")}}
+
判斷傳入的值是不是在 IEEE-754 雙精度範圍間 (即介於 -(253 - 1) 和 253 - 1之前)。
+
{{jsxref("Number.toInteger()")}} {{obsolete_inline}}
+
被用來評估傳入的值且將其轉換成整數 (或 {{jsxref("Global_Objects/Infinity", "Infinity")}}) 但已被移除。
+
{{jsxref("Number.parseFloat()")}}
+
這個方法和全域物件的 {{jsxref("parseFloat", "parseFloat()")}} 相同。
+
{{jsxref("Number.parseInt()")}}
+
這個方法和全域物件的 {{jsxref("parseInt", "parseInt()")}} 相同。
+
+ +

Number 實體

+ +

所有 Number 實體都會繼承其建構式的 {{jsxref("Number.prototype")}}。Number 的原型物件可以被修改並作用在所有 Number 實體。

+ +

方法

+ +
{{page('/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Number/prototype', '方法')}}
+ +

範例

+ +

使用 Number 物件去指派值給數值變數

+ +

下列的範例使用 Number 物件的屬性去指派值給數個數值變數:

+ +
var biggestNum = Number.MAX_VALUE;
+var smallestNum = Number.MIN_VALUE;
+var infiniteNum = Number.POSITIVE_INFINITY;
+var negInfiniteNum = Number.NEGATIVE_INFINITY;
+var notANum = Number.NaN;
+
+ +

Number 的整數範圍

+ +

下面的範例展示了最小和最大的整數,其可以被表示成 Number 物件(細節請參考 ECMAScript standard, chapter 8.5 The Number Type):

+ +
var biggestInt = 9007199254740992;
+var smallestInt = -9007199254740992;
+
+ +

當在解析已經被序列化的 JSON 的資料時,填入這個範圍之外的整數並且 JSON 剖析器強制將其轉成 Number 型別造成損壞是可預期的。將範圍之外的正數換成以 {{jsxref("String")}} 表示反倒是一個可行的替代方案。

+ +

使用 Number 轉換 Date 物件為 Unix 時間戳記

+ +

下面的範例將 Number 視為函式,並且使用它將 {{jsxref("Date")}} 轉換成時間戳記:

+ +
var d = new Date('December 17, 1995 03:24:00');
+console.log(Number(d)); // 819199440000
+
+
+ +

轉換數值字串成數值

+ +
Number("123")     // 123
+Number("12.3")    // 12.3
+Number("")        // 0
+Number("0x11")    // 17
+Number("0b11")    // 3
+Number("0o11")    // 9
+Number("foo")     // NaN
+Number("100a")    // NaN
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態註記
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7', 'Number')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number-objects', 'Number')}}{{Spec2('ES6')}}New methods and properties added: {{jsxref("Number.EPSILON", "EPSILON")}}, {{jsxref("Number.isFinite", "isFinite")}}, {{jsxref("Number.isInteger", "isInteger")}}, {{jsxref("Number.isNaN", "isNaN")}}, {{jsxref("Number.parseFloat", "parseFloat")}}, {{jsxref("Number.parseInt", "parseInt")}}
{{SpecName('ESDraft', '#sec-number-objects', 'Number')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/number/isfinite/index.html b/files/zh-tw/web/javascript/reference/global_objects/number/isfinite/index.html new file mode 100644 index 0000000000..a15d29c7c0 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/number/isfinite/index.html @@ -0,0 +1,93 @@ +--- +title: Number.isFinite() +slug: Web/JavaScript/Reference/Global_Objects/Number/isFinite +tags: + - JavaScript + - Method + - Number + - Reference +translation_of: Web/JavaScript/Reference/Global_Objects/Number/isFinite +--- +
{{JSRef}}
+ +

Number.isFinite() 方法會判斷傳入的值是否為有限數(finite number)。

+ +
{{EmbedInteractiveExample("pages/js/number-isfinite.html")}}
+ + + +

語法

+ +
Number.isFinite(value)
+ +

參數

+ +
+
value
+
The value to be tested for finiteness.
+
+ +

回傳值

+ +

A {{jsxref("Boolean")}} indicating whether or not the given value is a finite number.

+ +

說明

+ +

In comparison to the global {{jsxref("isFinite", "isFinite()")}} function, this method doesn't forcibly convert the parameter to a number. This means only values of the type number, that are also finite, return true.

+ +

範例

+ +
Number.isFinite(Infinity);  // false
+Number.isFinite(NaN);       // false
+Number.isFinite(-Infinity); // false
+
+Number.isFinite(0);         // true
+Number.isFinite(2e64);      // true
+
+Number.isFinite('0');       // false, would've been true with
+                            // global isFinite('0')
+Number.isFinite(null);      // false, would've been true with
+                            // global isFinite(null)
+
+ +

Polyfill

+ +
Number.isFinite = Number.isFinite || function(value) {
+    return typeof value === 'number' && isFinite(value);
+}
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-number.isfinite', 'Number.isInteger')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-number.isfinite', 'Number.isInteger')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.Number.isFinite")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/number/isnan/index.html b/files/zh-tw/web/javascript/reference/global_objects/number/isnan/index.html new file mode 100644 index 0000000000..9209e40779 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/number/isnan/index.html @@ -0,0 +1,99 @@ +--- +title: Number.isNaN() +slug: Web/JavaScript/Reference/Global_Objects/Number/isNaN +translation_of: Web/JavaScript/Reference/Global_Objects/Number/isNaN +--- +
{{JSRef}}
+ +

The Number.isNaN() method determines whether the passed value is {{jsxref("NaN")}} and its type is {{jsxref("Number")}}. It is a more robust version of the original, global {{jsxref("isNaN", "isNaN()")}}.

+ +
{{EmbedInteractiveExample("pages/js/number-isnan.html", "taller")}}
+ + + +

Syntax

+ +
Number.isNaN(value)
+ +

Parameters

+ +
+
value
+
The value to be tested for {{jsxref("NaN")}}.
+
+ +

Return value

+ +

true if the given value is {{jsxref("NaN")}} and its type is {{jsxref("Number")}}; otherwise, false.

+ +

Description

+ +

Due to both equality operators, {{jsxref("Operators/Comparison_Operators", "==", "#Equality")}} and {{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}, evaluating to false when checking if {{jsxref("NaN")}} is {{jsxref("NaN")}}, the function Number.isNaN() has become necessary. This situation is unlike all other possible value comparisons in JavaScript.

+ +

In comparison to the global {{jsxref("isNaN", "isNaN()")}} function, Number.isNaN() doesn't suffer the problem of forcefully converting the parameter to a number. This means it is now safe to pass values that would normally convert to {{jsxref("NaN")}}, but aren't actually the same value as {{jsxref("NaN")}}. This also means that only values of the type number, that are also {{jsxref("NaN")}}, return true.

+ +

Examples

+ +
Number.isNaN(NaN);        // true
+Number.isNaN(Number.NaN); // true
+Number.isNaN(0 / 0);      // true
+
+// e.g. these would have been true with global isNaN()
+Number.isNaN('NaN');      // false
+Number.isNaN(undefined);  // false
+Number.isNaN({});         // false
+Number.isNaN('blabla');   // false
+
+// These all return false
+Number.isNaN(true);
+Number.isNaN(null);
+Number.isNaN(37);
+Number.isNaN('37');
+Number.isNaN('37.37');
+Number.isNaN('');
+Number.isNaN(' ');
+
+ +

Polyfill

+ +

The following works because NaN is the only value in javascript which is not equal to itself.

+ +
Number.isNaN = Number.isNaN || function(value) {
+    return value !== value;
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-number.isnan', 'Number.isnan')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-number.isnan', 'Number.isnan')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Number.isNaN")}}

+ +

See also

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/number/prototype/index.html b/files/zh-tw/web/javascript/reference/global_objects/number/prototype/index.html new file mode 100644 index 0000000000..2a41977a2d --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/number/prototype/index.html @@ -0,0 +1,84 @@ +--- +title: Number.prototype +slug: Web/JavaScript/Reference/Global_Objects/Number/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Number +--- +
{{JSRef}}
+ +

Number.prototype 屬性用來表示 {{jsxref("Number")}} 建構式的原型。

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

說明

+ +

所有 {{jsxref("Number")}} 實體都繼承自 Number.prototype 。{{jsxref("Number")}} 建構式的原型物件可以被修改並作用在所有 {{jsxref("Number")}} 實體。

+ +

屬性

+ +
+
Number.prototype.constructor
+
回傳建立這個物件實體的建構式。預設為 {{jsxref("Number")}} 物件。
+
+ +

方法

+ +
+
{{jsxref("Number.prototype.toExponential()")}}
+
回傳以「科學記數法」表示的數值字串。
+
{{jsxref("Number.prototype.toFixed()")}}
+
回傳以定點表示的數值字串。
+
{{jsxref("Number.prototype.toLocaleString()")}}
+
回傳以當地語言為主的數值字串。這覆寫 {{jsxref("Object.prototype.toLocaleString()")}} 的方法。
+
{{jsxref("Number.prototype.toPrecision()")}}
+
回傳以定點或科學記數表示的數值字串。
+
{{jsxref("Number.prototype.toSource()")}} {{non-standard_inline}}
+
Returns an object literal representing the specified {{jsxref("Number")}} object; you can use this value to create a new object. Overrides the {{jsxref("Object.prototype.toSource()")}} method.
+
{{jsxref("Number.prototype.toString()")}}
+
回傳以特定基數表示的數值字串。這覆寫 {{jsxref("Object.prototype.toString()")}} 的方法 。
+
{{jsxref("Number.prototype.valueOf()")}}
+
回傳這個物件的原始型別,即原始數值。這覆寫 {{jsxref("Object.prototype.valueOf()")}} 。
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態註記
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.4', 'Number')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-properties-of-the-number-prototype-object', 'Number')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-properties-of-the-number-prototype-object', 'Number')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.Number.prototype")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/number/toexponential/index.html b/files/zh-tw/web/javascript/reference/global_objects/number/toexponential/index.html new file mode 100644 index 0000000000..622314ecfb --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/number/toexponential/index.html @@ -0,0 +1,164 @@ +--- +title: Number.prototype.toExponential() +slug: Web/JavaScript/Reference/Global_Objects/Number/toExponential +tags: + - 數字 + - 科學技數法 +translation_of: Web/JavaScript/Reference/Global_Objects/Number/toExponential +--- +
{{JSRef}}
+ +

toExponential() method 用來將數字轉成「科學記數法」格式。

+ +

語法

+ +
numObj.toExponential([fractionDigits])
+ +

參數

+ + + + + + + + + + + + + + + + + + + + +
參數可選默認值類型說明
fractionDigits默認盡可能將數字完整顯示{{jsxref("Number")}}(正整數)小數點後的位數。需為 0 至 20 之間。
+ +

回傳直

+ +

一 string,將數字以「科學計數法」格式表示出來

+ +

Exceptions

+ +
+
{{jsxref("RangeError")}}
+
若 fractionDigits 超出範圍(可接受的範圍是 0 ~ 20 之間的正整數)觸發 {{jsxref("RangeError")}}。
+
{{jsxref("TypeError")}}
+
若參數 fractionDigits 不是 {{jsxref("Number")}},則觸發{{jsxref("TypeError")}}。
+
+ +

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 {{jsxref("Number.prototype.toFixed", "toFixed()")}} method, which also applies to toExponential().

+ +

範例

+ +

Using toExponential

+ +
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
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.5.
{{SpecName('ES5.1', '#sec-15.7.4.6', 'Number.prototype.toExponential')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.prototype.toexponential', 'Number.prototype.toExponential')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-number.prototype.toexponential', 'Number.prototype.toExponential')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器支援度

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

延伸閱讀

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/number/tofixed/index.html b/files/zh-tw/web/javascript/reference/global_objects/number/tofixed/index.html new file mode 100644 index 0000000000..7a5afb608f --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/number/tofixed/index.html @@ -0,0 +1,108 @@ +--- +title: Number.prototype.toFixed() +slug: Web/JavaScript/Reference/Global_Objects/Number/toFixed +tags: + - JavaScript + - Method + - Number + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Number/toFixed +--- +
{{JSRef}}
+ +

toFixed() 方法會使用定點小數表示法(fixed-point notation)來格式化數字。

+ +
{{EmbedInteractiveExample("pages/js/number-tofixed.html")}}
+ + + +

語法

+ +
numObj.toFixed([digits])
+ +

參數

+ +
+
digits 小數位
+
選擇性輸入。顯示數值至多少個小數點,範圍由0到20之間,執行時或可支援非常大範圍的數值。如果無輸入會默認做0。
+
+ +

回傳值

+ +

一個代表以定點小數表示法(fixed-point notation)格式化數字後的字串。

+ +

例外

+ +
+
{{jsxref("RangeError")}}
+
If digits is too small or too large. Values between 0 and 100, inclusive, will not cause a {{jsxref("RangeError")}}. Implementations are allowed to support larger and smaller values as chosen.
+
{{jsxref("TypeError")}}
+
If this method is invoked on an object that is not a {{jsxref( "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 {{jsxref("Number.prototype.toString()")}} and returns a string in exponential notation.

+ +

範例

+ +

Using toFixed

+ +
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.23e+20).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)
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.5.
{{SpecName('ES5.1', '#sec-15.7.4.5', 'Number.prototype.toFixed')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-number.prototype.tofixed', 'Number.prototype.toFixed')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-number.prototype.tofixed', 'Number.prototype.toFixed')}}{{Spec2('ESDraft')}}
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.Number.toFixed")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/assign/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/assign/index.html new file mode 100644 index 0000000000..f4dfca5af7 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/assign/index.html @@ -0,0 +1,249 @@ +--- +title: Object.assign() +slug: Web/JavaScript/Reference/Global_Objects/Object/assign +translation_of: Web/JavaScript/Reference/Global_Objects/Object/assign +--- +
{{JSRef}}
+ +
Object.assign()被用來複製一個或多個物件自身所有可數的屬性到另一個目標物件。回傳的值為該目標物件。
+ +

語法

+ +
Object.assign(target, ...sources)
+ +

參數

+ +
+
target
+
目標物件
+
sources
+
來源物件
+
+ +

回傳值

+ +

     合併目標物件及(多個)來源物件所得到的最終物件。

+ +

說明

+ +

如果在目標物件裡的屬性名稱(key)和來源物件的屬性名稱相同,將會被覆寫。若來源物件之間又有相同的屬性名稱,則後者會將前者覆寫。

+ +

Object.assign()只會從來源物件將自身可列舉的屬性複製到目標物件。此函式方法(method) 使用來源物件的[[Get]]事件和目標物件的[[Set]]事件,使它將會執行getters和setters。因此,這邊的指派(assigns)屬性不只是複製或定義新屬性。若在合併包含getters的來源物件時,這個事件可能就不適合用來合併屬性。至於複製屬性的定義(包含其可列舉性)到各屬性,反倒是會用到 {{jsxref("Object.getOwnPropertyDescriptor()")}} 和 {{jsxref("Object.defineProperty()")}} 。

+ +

{{jsxref("String")}} 和 {{jsxref("Symbol")}} 類型的屬性都會被複製。

+ +

若發生錯誤,例如: 當一個屬性不可被寫入時,將會引發 {{jsxref("TypeError")}} 的錯誤,且目標物件剩餘的屬性將不會改變。

+ +

注意: Object.assign() 不會在來源物件屬性的值為{{jsxref("null")}} 或 {{jsxref("undefined")}} 的時候拋出錯誤。

+ +

範例

+ +

複製物件

+ +
var obj = { a: 1 };
+var copy = Object.assign({}, obj);
+console.log(copy); // { a: 1 }
+
+ +

警告:非深層複製

+ +

深層複製(deep clone)需要使用其他的替代方案,因為 Object.assign() 僅複製屬性值。若來源物件的值參照到一個子物件,它只會複製該子物件的參照。

+ +
function test() {
+  let a = { b: {c:4} , d: { e: {f:1}} }
+  let g = Object.assign({},a) // 淺層
+  let h = JSON.parse(JSON.stringify(a)); // 深層
+  console.log(g.d) // { e: { f: 1 } }
+  g.d.e = 32
+  console.log('g.d.e set to 32.') // g.d.e set to 32.
+  console.log(g) // { b: { c: 4 }, d: { e: 32 } }
+  console.log(a) // { b: { c: 4 }, d: { e: 32 } }
+  console.log(h) // { b: { c: 4 }, d: { e: { f: 1 } } }
+  h.d.e = 54
+  console.log('h.d.e set to 54.') // h.d.e set to 54.
+  console.log(g) // { b: { c: 4 }, d: { e: 32 } }
+  console.log(a) // { b: { c: 4 }, d: { e: 32 } }
+  console.log(h) // { b: { c: 4 }, d: { e: 54 } }
+}
+test();
+
+ +

合併物件

+ +
var o1 = { a: 1 };
+var o2 = { b: 2 };
+var o3 = { c: 3 };
+
+var obj = Object.assign(o1, o2, o3);
+console.log(obj); // { a: 1, b: 2, c: 3 }
+console.log(o1);  // { a: 1, b: 2, c: 3 }, 目標物件本身也被改變。
+ +

有相同屬性時合併物件

+ +
var o1 = { a: 1, b: 1, c: 1 };
+var o2 = { b: 2, c: 2 };
+var o3 = { c: 3 };
+
+var obj = Object.assign({}, o1, o2, o3);
+console.log(obj); // { a: 1, b: 2, c: 3 },屬性c為o3.c的值,最後一個出現的屬性c。
+ +

所有的屬性會被後方相同屬性名稱的值覆寫。

+ +

複製 Symbol 型別的屬性

+ +
var o1 = { a: 1 };
+var o2 = { [Symbol('foo')]: 2 };
+
+var obj = Object.assign({}, o1, o2);
+console.log(obj); // { a : 1, [Symbol("foo")]: 2 } (cf. bug 1207182 on Firefox)
+Object.getOwnPropertySymbols(obj); // [Symbol(foo)]非不在
+
+ +

在屬性鏈中的不可列舉屬性不會被複製

+ +
var obj = Object.create({ foo: 1 }, { // foo 是 obj 的屬性鏈。
+  bar: {
+    value: 2  // bar 是不可列舉的屬性,因為enumerable預設為false。
+  },
+  baz: {
+    value: 3,
+    enumerable: true  // baz 是自身可列舉的屬性。
+  }
+});
+
+var copy = Object.assign({}, obj);
+console.log(copy); // { baz: 3 }
+
+ +

原始型別會被包成物件

+ +
var v1 = 'abc';
+var v2 = true;
+var v3 = 10;
+var v4 = Symbol('foo');
+
+var obj = Object.assign({}, v1, null, v2, undefined, v3, v4);
+// 原始型別會被打包,null和undefined則會被忽略。
+// 注意: 只有打包成物件的字串是可列舉的,即可被複製的。
+console.log(obj); // { "0": "a", "1": "b", "2": "c" }
+
+ +

任何異常將會中斷正進行的複製程序

+ +
var target = Object.defineProperty({}, 'foo', {
+  value: 1,
+  writable: false
+}); // target.foo 是 read-only (唯讀)屬性
+
+Object.assign(target, { bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 });
+// TypeError: "foo" 是 read-only
+// 在指派值給 target.foo 時,異常(Exception)會被拋出。
+
+console.log(target.bar);  // 2, 第一個來源物件複製成功。
+console.log(target.foo2); // 3, 第二個來源物件的第一個屬性複製成功。
+console.log(target.foo);  // 1, 異常在這裡拋出。
+console.log(target.foo3); // undefined, 複製程式已中斷,複製失敗。
+console.log(target.baz);  // undefined, 第三個來源物件也不會被複製。
+
+ +

複製的存取程序

+ +
var obj = {
+  foo: 1,
+  get bar() {
+    return 2;
+  }
+};
+
+var copy = Object.assign({}, obj);
+console.log(copy);
+// { foo: 1, bar: 2 }, copy.bar的值,是obj.bar的getter回傳的值。
+
+// 這個函式用來複製完整的描述內容。
+function completeAssign(target, ...sources) {
+  sources.forEach(source => {
+    let descriptors = Object.keys(source).reduce((descriptors, key) => {
+      descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
+      return descriptors;
+    }, {});
+    // Object.assign 預設會複製可列舉的Symbols。
+    Object.getOwnPropertySymbols(source).forEach(sym => {
+      let descriptor = Object.getOwnPropertyDescriptor(source, sym);
+      if (descriptor.enumerable) {
+        descriptors[sym] = descriptor;
+      }
+    });
+    Object.defineProperties(target, descriptors);
+  });
+  return target;
+}
+
+var copy = completeAssign({}, obj);
+console.log(copy);
+// { foo:1, get bar() { return 2 } }
+
+ +

Polyfill

+ +

{{Glossary("Polyfill","polyfill")}} 不支援Symbol屬性,因為ES5沒有Symbol型別。

+ +
if (typeof Object.assign != 'function') {
+  Object.assign = function (target, varArgs) { // .length of function is 2
+    'use strict';
+    if (target == null) { // TypeError if undefined or null
+      throw new TypeError('Cannot convert undefined or null to object');
+    }
+
+    var to = Object(target);
+
+    for (var index = 1; index < arguments.length; index++) {
+      var nextSource = arguments[index];
+
+      if (nextSource != null) { // Skip over if undefined or null
+        for (var nextKey in nextSource) {
+          // Avoid bugs when hasOwnProperty is shadowed
+          if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
+            to[nextKey] = nextSource[nextKey];
+          }
+        }
+      }
+    }
+    return to;
+  };
+}
+
+ +

規格

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-object.assign', 'Object.assign')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-object.assign', 'Object.assign')}}{{Spec2('ESDraft')}}
+ +

瀏覽器相容性

+ +
{{Compat("javascript.builtins.Object.assign")}}
+ +
+ +

參閱

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/create/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/create/index.html new file mode 100644 index 0000000000..f158d36977 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/create/index.html @@ -0,0 +1,258 @@ +--- +title: Object.create() +slug: Web/JavaScript/Reference/Global_Objects/Object/create +translation_of: Web/JavaScript/Reference/Global_Objects/Object/create +--- +
{{JSRef}}
+ +

Object.create() 指定其原型物件與屬性,創建一個新物件。

+ +

語法

+ +
Object.create(proto[, propertiesObject])
+ +

參數

+ +
+
proto
+
指定新物件的原型 (prototype) 物件。
+
propertiesObject
+
選用,為一物件。如有指定且非 {{jsxref("undefined")}},則此參數物件中可列舉出的屬性 (即參數物件自身定義的屬性,並非指原型鏈上的 enumerable 特性 ) 對應其屬性名稱,根據其屬性敘述元 (property descriptors) 加進新創建的物件。這些屬性對應到 {{jsxref("Object.defineProperties()")}} 的第二個參數。
+
+ +

回傳

+ +

具有指定原型物件與屬性的新物件。

+ +

例外

+ +

 如果 proto 參數不是 {{jsxref("null")}} 或一個物件,將會拋出 {{jsxref("TypeError")}} 例外。

+ +

範例

+ +

使用 Object.create() 實現類別繼承

+ +

下方是如何使用 Object.create() 去實現類別繼承的示範,此為 JavaScript 支援的單一繼承.。

+ +
// Shape - 父類別
+function Shape() {
+  this.x = 0;
+  this.y = 0;
+}
+
+// 父類別的方法
+Shape.prototype.move = function(x, y) {
+  this.x += x;
+  this.y += y;
+  console.info('Shape moved.');
+};
+
+// Rectangle - 子類別
+function Rectangle() {
+  Shape.call(this); // call super constructor.
+}
+
+// 子類別擴展(extends)父類別
+Rectangle.prototype = Object.create(Shape.prototype);
+Rectangle.prototype.constructor = Rectangle;
+
+var rect = new Rectangle();
+
+console.log('Is rect an instance of Rectangle?', rect instanceof Rectangle);// true
+console.log('Is rect an instance of Shape?', rect instanceof Shape);// true
+rect.move(1, 1); // Outputs, 'Shape moved.'
+
+ +

也可像 mixin 繼承多個物件。

+ +
function MyClass() {
+  SuperClass.call(this);
+  OtherSuperClass.call(this);
+}
+
+// 繼承一個父類別
+MyClass.prototype = Object.create(SuperClass.prototype);
+// mixin另一個父類別
+Object.assign(MyClass.prototype, OtherSuperClass.prototype);
+// 重新指定建構式
+MyClass.prototype.constructor = MyClass;
+
+MyClass.prototype.myMethod = function() {
+  // do a thing
+};
+
+ +

Object.assign 複製 OtherSuperClass 原型上的所有屬性到 MyClass 的原型上,使所有 MyClass 的實例都能使用。Object.assign 為 ES2015 標準且有 polyfill。如需支援較舊的瀏覽器,可使用第三方套件實現如 jQuery.extend() 或 _.assign() 。

+ +

propertiesObject 參數的使用

+ +
var o;
+
+// 建立以null為原型的物件
+o = Object.create(null);
+
+
+o = {};
+// 等同於:
+o = Object.create(Object.prototype);
+
+
+// Example where we create an object with a couple of sample properties.
+// (Note that the second parameter maps keys to *property descriptors*.)
+o = Object.create(Object.prototype, {
+  // foo 為數值屬性
+  foo: { writable: true, configurable: true, value: 'hello' },
+  // bar 為 getter-and-setter 訪問屬性
+  bar: {
+    configurable: false,
+    get: function() { return 10; },
+    set: function(value) { console.log('Setting `o.bar` to', value); }
+/* with ES5 Accessors our code can look like this
+    get function() { return 10; },
+    set function(value) { console.log('setting `o.bar` to', value); } */
+  }
+});
+
+
+function Constructor() {}
+o = new Constructor();
+// 等同於:
+o = Object.create(Constructor.prototype);
+// Of course, if there is actual initialization code in the
+// Constructor function, the Object.create() cannot reflect it
+
+
+// 創建一個新物件,指定原型是全新的空物件,並加入值為 42 的屬性'p'
+o = Object.create({}, { p: { value: 42 } });
+
+// 屬性敘述元 writable, enumerable , configurable 未定義,預設皆為 false
+o.p = 24;
+o.p;
+// 42
+
+o.q = 12;
+for (var prop in o) {
+  console.log(prop);
+}
+// 'q'
+
+delete o.p;
+// false
+
+// to specify an ES3 property
+o2 = Object.create({}, {
+  p: {
+    value: 42,
+    writable: true,
+    enumerable: true,
+    configurable: true
+  }
+});
+
+ +

Polyfill

+ +

此 polyfill 涵蓋了主要的使用情境:指定一個原型創建一個新的物件,第二個參數為選用。

+ +

要注意的是在 ES5 的Object.create中, [[Prototype]] 可以為 null,但在ECMAScript 5 以前的版本,polyfill 會因為繼承限制( limitation inherent )而不支援此情形。

+ +
if (typeof Object.create !== "function") {
+    Object.create = function (proto, propertiesObject) {
+        if (!(proto === null || typeof proto === "object" || typeof proto === "function")) {
+            throw TypeError('Argument must be an object, or null');
+        }
+        var temp = new Object();
+        temp.__proto__ = proto;
+        if(typeof propertiesObject === "object")
+            Object.defineProperties(temp, propertiesObject);
+        return temp;
+    };
+}
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.5', 'Object.create')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.create', 'Object.create')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.create', 'Object.create')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("5")}}{{CompatGeckoDesktop("2")}}{{CompatIE("9")}}{{CompatOpera("11.60")}}{{CompatSafari("5")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("2")}}{{CompatVersionUnknown}}{{CompatOperaMobile("11.5")}}{{CompatVersionUnknown}}
+
+ +

參閱

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/defineproperties/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/defineproperties/index.html new file mode 100644 index 0000000000..fc87ca0317 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/defineproperties/index.html @@ -0,0 +1,224 @@ +--- +title: Object.defineProperties() +slug: Web/JavaScript/Reference/Global_Objects/Object/defineProperties +translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperties +--- +
{{JSRef}}
+ +

Object.defineProperties() 函式可定義新的或是修改已存在的物件屬性,並回傳修改後的物件。

+ +

語法

+ +
Object.defineProperties(obj, props)
+ +

參數

+ +
+
obj
+
The object on which to define or modify properties.
+
props
+
An object whose own enumerable properties constitute descriptors for the properties to be defined or modified. Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors (see {{jsxref("Object.defineProperty()")}} for more details). Descriptors have the following keys:
+
+
+
configurable
+
true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.
+ 預設為 false.
+
enumerable
+
若該屬性設為 true,則該屬性可被物件所列舉。
+ 預設為 false.
+
+ +
+
value
+
The value associated with the property. Can be any valid JavaScript value (number, object, function, etc).
+ 預設為 {{jsxref("undefined")}}.
+
writable
+
若該屬性為 true,則該屬性可透過{{jsxref("Operators/Assignment_Operators", "賦予運算子", "", 1)}}所改變
+ 預設為 false.
+
+ +
+
get
+
A function which serves as a getter for the property, or {{jsxref("undefined")}} if there is no getter. The function return will be used as the value of property.
+ 預設為 {{jsxref("undefined")}}.
+
set
+
A function which serves as a setter for the property, or {{jsxref("undefined")}} if there is no setter. The function will receive as only argument the new value being assigned to the property.
+ 預設為 {{jsxref("undefined")}}.
+
+
+
+ +

回傳值

+ +

The object that was passed to the function.

+ +

描述

+ +

Object.defineProperties, in essence, defines all properties corresponding to the enumerable own properties of props on the object obj object.

+ +

範例

+ +
var obj = {};
+Object.defineProperties(obj, {
+  'property1': {
+    value: true,
+    writable: true
+  },
+  'property2': {
+    value: 'Hello',
+    writable: false
+  }
+  // etc. etc.
+});
+
+ +

Polyfill

+ +

Assuming a pristine execution environment with all names and properties referring to their initial values, Object.defineProperties is almost completely equivalent (note the comment in isCallable) to the following reimplementation in JavaScript:

+ +
function defineProperties(obj, properties) {
+  function convertToDescriptor(desc) {
+    function hasProperty(obj, prop) {
+      return Object.prototype.hasOwnProperty.call(obj, prop);
+    }
+
+    function isCallable(v) {
+      // NB: modify as necessary if other values than functions are callable.
+      return typeof v === 'function';
+    }
+
+    if (typeof desc !== 'object' || desc === null)
+      throw new TypeError('bad desc');
+
+    var d = {};
+
+    if (hasProperty(desc, 'enumerable'))
+      d.enumerable = !!desc.enumerable;
+    if (hasProperty(desc, 'configurable'))
+      d.configurable = !!desc.configurable;
+    if (hasProperty(desc, 'value'))
+      d.value = desc.value;
+    if (hasProperty(desc, 'writable'))
+      d.writable = !!desc.writable;
+    if (hasProperty(desc, 'get')) {
+      var g = desc.get;
+
+      if (!isCallable(g) && typeof g !== 'undefined')
+        throw new TypeError('bad get');
+      d.get = g;
+    }
+    if (hasProperty(desc, 'set')) {
+      var s = desc.set;
+      if (!isCallable(s) && typeof s !== 'undefined')
+        throw new TypeError('bad set');
+      d.set = s;
+    }
+
+    if (('get' in d || 'set' in d) && ('value' in d || 'writable' in d))
+      throw new TypeError('identity-confused descriptor');
+
+    return d;
+  }
+
+  if (typeof obj !== 'object' || obj === null)
+    throw new TypeError('bad obj');
+
+  properties = Object(properties);
+
+  var keys = Object.keys(properties);
+  var descs = [];
+
+  for (var i = 0; i < keys.length; i++)
+    descs.push([keys[i], convertToDescriptor(properties[keys[i]])]);
+
+  for (var i = 0; i < descs.length; i++)
+    Object.defineProperty(obj, descs[i][0], descs[i][1]);
+
+  return obj;
+}
+
+ +

規格

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatus註記
{{SpecName('ES5.1', '#sec-15.2.3.7', 'Object.defineProperties')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5
{{SpecName('ES6', '#sec-object.defineproperties', 'Object.defineProperties')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.defineproperties', 'Object.defineProperties')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop("2")}}{{CompatChrome("5")}}{{CompatIE("9")}}{{CompatOpera("11.60")}}{{CompatSafari("5")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatGeckoMobile("2")}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatOperaMobile("11.5")}}{{CompatVersionUnknown}}
+
+ +

參閱

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/defineproperty/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/defineproperty/index.html new file mode 100644 index 0000000000..cf83590181 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/defineproperty/index.html @@ -0,0 +1,380 @@ +--- +title: Object.defineProperty() +slug: Web/JavaScript/Reference/Global_Objects/Object/defineProperty +translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperty +--- +
{{JSRef}}
+ +

靜態方法 Object.defineProperty() 會直接對一個物件定義、或是修改現有的屬性。執行後會回傳定義完的物件。

+ +
+

注:這個方法會直接針對 {{jsxref("Object")}} 呼叫建構子(constructor),而不是 Object 型別的實例。

+
+ +
{{EmbedInteractiveExample("pages/js/object-defineproperty.html")}}
+ +

語法

+ +
Object.defineProperty(obj, prop, descriptor)
+ +

參數

+ +
+
obj
+
要定義屬性的物件。
+
prop
+
要被定義或修改的屬性名字。
+
descriptor
+
要定義或修改物件敘述內容。
+
+ +

回傳值

+ +

被定義完或修改完屬性的物件。

+ +

描述

+ +

這個函式可以用來增加或修改物件中的屬性定義。在物件建立屬性後,這些屬性同時有被設定預設的設定,才能讓這些屬性被列舉、改變和刪除。而這個函式可以用來改變這些預設的設定。根據預設,被加到物件且使用Object.defineProperty()的值都是{{glossary("Immutable")}}。

+ +

物件內的屬性描述器(Property descriptor)主要有兩種:資料描述器(data descriptor)與訪問描述器(accessor descriptor)。資料描述器(data descriptor)是可以選擇能否覆寫的屬性。訪問描述器(accessor descriptor) is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both.

+ +

data 和 accessor descriptors 皆為物件,兩者共享下面提及的 key:

+ +
+
configurable
+
true 則若且唯若此屬性則將可改變或刪除自相應物件。
+ 預設為 false
+
enumerable
+
true 如果且唯若相應物件被列舉,將會列舉此屬性。
+ 預設為 false
+
+ +

一個 data descriptor 還有以下可選的 key:

+ +
+
value
+
The value associated with the property. Can be any valid JavaScript value (number, object, function, etc).
+ 預設 {{jsxref("undefined")}}.
+
writable
+
true 則該物件屬性可透過{{jsxref("Operators/Assignment_Operators", "賦予運算子", "", 1)}}改變其值。
+ 預設 false
+
+ +

一個 accessor descriptor 也擁有下述之 optional keys:

+ +
+
get
+
作為 getter 形式,為屬性存在的函式,如果沒有 getter 的話則回傳 {{jsxref("undefined")}}。函式回傳將用於屬性值。
+ 預設 {{jsxref("undefined")}}
+
set
+
作為 setter 形式,為屬性存在的函式,如果沒有 setter 的話則回傳 {{jsxref("undefined")}}。 The function will receive as only argument the new value being assigned to the property.
+ 預設 {{jsxref("undefined")}}
+
+ +

請注意,這些選項並不一定要是 descriptor 屬性,由原型鍊(prototype chain)繼承的屬性,也會被考慮到。要確保需要凍結(freeze)的 {{jsxref("Object.prototype")}} upfront 預設能被保存,請明確指定所有選項,或把 {{jsxref("Object.prototype.__proto__", "__proto__")}} 屬性指向 {{jsxref("null")}}。

+ +
// using __proto__
+var obj = {};
+Object.defineProperty(obj, 'key', {
+  __proto__: null, // no inherited properties
+  value: 'static'  // not enumerable
+                   // not configurable
+                   // not writable
+                   // as defaults
+});
+
+// being explicit
+Object.defineProperty(obj, 'key', {
+  enumerable: false,
+  configurable: false,
+  writable: false,
+  value: 'static'
+});
+
+// recycling same object
+function withValue(value) {
+  var d = withValue.d || (
+    withValue.d = {
+      enumerable: false,
+      writable: false,
+      configurable: false,
+      value: null
+    }
+  );
+  d.value = value;
+  return d;
+}
+// ... and ...
+Object.defineProperty(obj, 'key', withValue('static'));
+
+// if freeze is available, prevents adding or
+// removing the object prototype properties
+// (value, get, set, enumerable, writable, configurable)
+(Object.freeze || Object)(Object.prototype);
+
+ +

範例

+ +

If you want to see how to use the Object.defineProperty method with a binary-flags-like syntax, see additional examples.

+ +

建立屬性

+ +

When the property specified doesn't exist in the object, Object.defineProperty() creates a new property as described. Fields may be omitted from the descriptor, and default values for those fields are imputed. All of the Boolean-valued fields default to false. The value, get, and set fields default to {{jsxref("undefined")}}. A property which is defined without get/set/value/writable is called “generic” and is “typed” as a data descriptor.

+ +
var o = {}; // Creates a new object
+
+// Example of an object property added with defineProperty with a data property descriptor
+Object.defineProperty(o, 'a', {
+  value: 37,
+  writable: true,
+  enumerable: true,
+  configurable: true
+});
+// 'a' property exists in the o object and its value is 37
+
+// Example of an object property added with defineProperty with an accessor property descriptor
+var bValue = 38;
+Object.defineProperty(o, 'b', {
+  get: function() { return bValue; },
+  set: function(newValue) { bValue = newValue; },
+  enumerable: true,
+  configurable: true
+});
+o.b; // 38
+// 'b' property exists in the o object and its value is 38
+// The value of o.b is now always identical to bValue, unless o.b is redefined
+
+// You cannot try to mix both:
+Object.defineProperty(o, 'conflict', {
+  value: 0x9f91102,
+  get: function() { return 0xdeadbeef; }
+});
+// throws a TypeError: value appears only in data descriptors, get appears only in accessor descriptors
+
+ +

修改屬性

+ +

如果該屬性已經存在, Object.defineProperty() 將會根據描述符內的值和物件當前的 configuration 來修改屬性。 如果舊的描述符之 configurable 的特徵為 false (屬性為 “non-configurable”), 那除了 writable 之外的特徵都將無法修改。 在這個情況,也不可能在 data 和 accessor 屬性類型中來回切換。

+ +

如果有一個屬性是 non-configurable, 那它的 writable 特徵只能被改變為 false.

+ +

若嘗試改變 non-configurable property attributes,將會丟出一個 {{jsxref("TypeError")}},除非當前之值與新值相同。

+ +

Writable attribute

+ +

當 writable 屬性特徵被設為 false, 此屬性為 “non-writable”. 它將無法被重新賦值。

+ +
var o = {}; // Creates a new object
+
+Object.defineProperty(o, 'a', {
+  value: 37,
+  writable: false
+});
+
+console.log(o.a); // logs 37
+o.a = 25; // No error thrown (it would throw in strict mode, even if the value had been the same)
+console.log(o.a); // logs 37. The assignment didn't work.
+
+ +

As seen in the example, trying to write into the non-writable property doesn't change it but doesn't throw an error either.

+ +

可列舉 attribute

+ +

The enumerable property attribute defines whether the property shows up in a {{jsxref("Statements/for...in", "for...in")}} loop and {{jsxref("Object.keys()")}} or not.

+ +
var o = {};
+Object.defineProperty(o, 'a', { value: 1, enumerable: true });
+Object.defineProperty(o, 'b', { value: 2, enumerable: false });
+Object.defineProperty(o, 'c', { value: 3 }); // enumerable defaults to false
+o.d = 4; // enumerable defaults to true when creating a property by setting it
+
+for (var i in o) {
+  console.log(i);
+}
+// logs 'a' and 'd' (in undefined order)
+
+Object.keys(o); // ['a', 'd']
+
+o.propertyIsEnumerable('a'); // true
+o.propertyIsEnumerable('b'); // false
+o.propertyIsEnumerable('c'); // false
+
+ +

可設定 attribute

+ +

The configurable attribute controls at the same time whether the property can be deleted from the object and whether its attributes (other than writable) can be changed.

+ +
var o = {};
+Object.defineProperty(o, 'a', {
+  get: function() { return 1; },
+  configurable: false
+});
+
+Object.defineProperty(o, 'a', { configurable: true }); // throws a TypeError
+Object.defineProperty(o, 'a', { enumerable: true }); // throws a TypeError
+Object.defineProperty(o, 'a', { set: function() {} }); // throws a TypeError (set was undefined previously)
+Object.defineProperty(o, 'a', { get: function() { return 1; } }); // throws a TypeError (even though the new get does exactly the same thing)
+Object.defineProperty(o, 'a', { value: 12 }); // throws a TypeError
+
+console.log(o.a); // logs 1
+delete o.a; // Nothing happens
+console.log(o.a); // logs 1
+
+ +

If the configurable attribute of o.a had been true, none of the errors would be thrown and the property would be deleted at the end.

+ +

新增多個屬性及賦予初始值

+ +

It's important to consider the way default values of attributes are applied. There is often a difference between simply using dot notation to assign a value and using Object.defineProperty(), as shown in the example below.

+ +
var o = {};
+
+o.a = 1;
+// is equivalent to:
+Object.defineProperty(o, 'a', {
+  value: 1,
+  writable: true,
+  configurable: true,
+  enumerable: true
+});
+
+
+// On the other hand,
+Object.defineProperty(o, 'a', { value: 1 });
+// is equivalent to:
+Object.defineProperty(o, 'a', {
+  value: 1,
+  writable: false,
+  configurable: false,
+  enumerable: false
+});
+
+ +

Custom Setters and Getters

+ +

Example below shows how to implement a self-archiving object. When temperature property is set, the archive array gets a log entry.

+ +
function Archiver() {
+  var temperature = null;
+  var archive = [];
+
+  Object.defineProperty(this, 'temperature', {
+    get: function() {
+      console.log('get!');
+      return temperature;
+    },
+    set: function(value) {
+      temperature = value;
+      archive.push({ val: temperature });
+    }
+  });
+
+  this.getArchive = function() { return archive; };
+}
+
+var arc = new Archiver();
+arc.temperature; // 'get!'
+arc.temperature = 11;
+arc.temperature = 13;
+arc.getArchive(); // [{ val: 11 }, { val: 13 }]
+
+ +

or

+ +
var pattern = {
+    get: function () {
+        return 'I always return this string, whatever you have assigned';
+    },
+    set: function () {
+        this.myname = 'this is my name string';
+    }
+};
+
+
+function TestDefineSetAndGet() {
+    Object.defineProperty(this, 'myproperty', pattern);
+}
+
+
+var instance = new TestDefineSetAndGet();
+instance.myproperty = 'test';
+console.log(instance.myproperty); // I always return this string, whatever you have assigned
+
+console.log(instance.myname); // this is my name string
+
+
+ +

規格

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatus註記
{{SpecName('ES5.1', '#sec-15.2.3.6', 'Object.defineProperty')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.defineproperty', 'Object.defineProperty')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.defineproperty', 'Object.defineProperty')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Object.defineProperty")}}

+
+ +

Compatibility notes

+ +

Redefining the length property of an Array object

+ +

It is possible to redefine the {{jsxref("Array.length", "length")}} property of arrays, subject to the usual redefinition restrictions. (The {{jsxref("Array.length", "length")}} property is initially non-configurable, non-enumerable, and writable. Thus on an unaltered array, it's possible to change the {{jsxref("Array.length", "length")}} property's value or to make it non-writable. It is not allowed to change its enumerability or configurability, or if it is non-writable to change its value or writability.) However, not all browsers permit this redefinition.

+ +

Firefox 4 through 22 will throw a {{jsxref("TypeError")}} on any attempt whatsoever (whether permitted or not) to redefine the {{jsxref("Array.length", "length")}} property of an array.

+ +

Versions of Chrome which implement Object.defineProperty() in some circumstances ignore a length value different from the array's current {{jsxref("Array.length", "length")}} property. In some circumstances changing writability seems to silently not work (and not throw an exception). Also, relatedly, some array-mutating methods like {{jsxref("Array.prototype.push")}} don't respect a non-writable length.

+ +

Versions of Safari which implement Object.defineProperty() ignore a length value different from the array's current {{jsxref("Array.length", "length")}} property, and attempts to change writability execute without error but do not actually change the property's writability.

+ +

Only Internet Explorer 9 and later, and Firefox 23 and later, appear to fully and correctly implement redefinition of the {{jsxref("Array.length", "length")}} property of arrays. For now, don't rely on redefining the {{jsxref("Array.length", "length")}} property of an array to either work, or to work in a particular manner. And even when you can rely on it, there's really no good reason to do so.

+ +

Internet Explorer 8 specific notes

+ +

Internet Explorer 8 implemented a Object.defineProperty() method that could only be used on DOM objects. A few things need to be noted:

+ + + +

參閱

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/freeze/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/freeze/index.html new file mode 100644 index 0000000000..0c26b9f308 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/freeze/index.html @@ -0,0 +1,198 @@ +--- +title: Object.freeze() +slug: Web/JavaScript/Reference/Global_Objects/Object/freeze +translation_of: Web/JavaScript/Reference/Global_Objects/Object/freeze +--- +
{{JSRef}}
+ +

 

+ +

Object.freeze() 顧名思義是用來「凍結」一個物件的: 也就是防止物件新增屬性; 防止物件既有的屬性被刪除; 防止物件原本的屬性, 還有屬性的可列舉性, 可設定性, 可寫性被改動; 同時它也防止物件的原型被改變。此方法回傳一個凍結狀態的物件。

+ +
{{EmbedInteractiveExample("pages/js/object-freeze.html")}}
+ +

語法

+ +
Object.freeze(obj)
+ +

參數

+ +
+
obj
+
要被凍結的物件
+
+ +

回傳值

+ +

被凍結的物件

+ +

描述

+ +

一個被凍結的物件無法被新增或刪除屬性。任何想要改動的嘗試都會失敗, 要不沈默地失敗, 就是丟出一個 {{jsxref("TypeError")}} 例外 (此例外最常出現在 {{jsxref("Strict_mode", "strict mode", "", 1)}})

+ +

資料屬性無法被改變。訪問者方法 - setters 也一樣不能改變資料屬性 (雖然它會給你可以改變資料值的假象)。注意! 如果資料屬性是物件的話,該物件的值是可以被改變的,除非它們也被凍結。一個陣列同樣可以被凍結 (因為它也是一個物件),被凍結後它的元素內容就不能被改變,也不能新增或刪除元素。

+ +

範例

+ +

凍結物件

+ +
var obj = {
+  prop: function() {},
+  foo: 'bar'
+};
+
+// 新的屬性可以被新增,原本的屬性可以被改變或刪除
+obj.foo = 'baz';
+obj.lumpy = 'woof';
+delete obj.prop;
+
+// 回傳的物件跟原本傳入的物件是同一個,所以不需要記住回傳值
+// 也可以凍結一個物件
+var o = Object.freeze(obj);
+
+o === obj; // true
+Object.isFrozen(obj); // === true
+
+// 現在任何改動都會失敗
+obj.foo = 'quux'; // 什麼事也不會發生
+// 屬性無法被新增
+obj.quaxxor = 'the friendly duck';
+
+// 在嚴格模式中,如方才的嘗試都會丟出 TypeError
+function fail(){
+  'use strict';
+  obj.foo = 'sparky'; // 丟出 TypeError
+  delete obj.foo; // 丟出 TypeError
+  delete obj.quaxxor; // 回傳 true 因為屬性 'quaxxor' 從來沒有被新增
+  obj.sparky = 'arf'; // 丟出 TypeError
+}
+
+fail();
+
+// 嘗試透過 Object.defineProperty 來改變屬性的值會丟出 TypeError
+Object.defineProperty(obj, 'ohai', { value: 17 });
+Object.defineProperty(obj, 'foo', { value: 'eit' });
+
+// 一樣不可能改變物件的原型,都會丟出 TypeError
+Object.setPrototypeOf(obj, { x: 20 })
+obj.__proto__ = { x: 20 }
+
+ +

凍結陣列

+ +
let a = [0];
+Object.freeze(a); // 現在這個陣列不能被改動
+
+a[0]=1; // 沈默地失敗
+a.push(2); // 沈默地失敗
+
+// 在嚴格模式底下會丟出 TypeError
+function fail() {
+  "use strict"
+  a[0] = 1;
+  a.push(2);
+}
+
+fail();
+ +

被凍結的物件是不可變 (Immutable) 的。然而,它並不等於常數 (constant)。以下的範例顯示一個被凍結的物件並不是常數 (凍結的動作是「淺」的 - 如果資料屬性也是物件, 不會遞迴地做凍結的動作)。

+ +
obj1 = {
+  internal: {}
+};
+
+Object.freeze(obj1);
+obj1.internal.a = 'aValue';
+
+obj1.internal.a // 'aValue'
+ +

如果要成為一個常數物件,整個物件參考圖 (包含直接指向或間接指向其他物件) 必須都只能指向被凍結的不可變物件。一個物件被稱作不可變是因為它的整個物件狀態 (值或是指向其他物件的參考) 是固定的。注意,string, number 和 boolean 這些原始型別的值是永遠不變的,Function 和 Array 都屬於物件的一種。

+ +

要讓一個物件變成常數物件,就必須遞迴地凍結每個是物件型別的屬性 (稱作深凍結)。只有當你知道物件的參考圖不存在任何循環 的時候才能使用以上遞迴的方式來凍結物件,不然就可能會造成無窮迴圈。一個改善以下範例中 deepFreeze() 來解決無窮迴圈問題的方法是 - 創建一個接受一個路徑參數 (像是陣列) 的內部用函數,用來避免無窮遞迴地呼叫 deepFreeze() - 當發現欲凍結的物件已經出現在之前凍結的物件行列中就不繼續遞迴下去。需要注意的是你可能會不小心凍結一個不應該被凍結的物件,像是 [window]。

+ +
// 用這個函數來進行對物件的深凍結
+function deepFreeze(obj) {
+
+  // 取得物件的所有屬性名稱
+  var propNames = Object.getOwnPropertyNames(obj);
+
+  // 在凍結物件本身之前先凍結物件的所有物件屬性
+  propNames.forEach(function(name) {
+    var prop = obj[name];
+
+    // 凍結 prop 如果它是一個物件
+    if (typeof prop == 'object' && prop !== null)
+      deepFreeze(prop);
+  });
+
+  // 凍結本身 (no-op 如果已經被凍結了)
+  return Object.freeze(obj);
+}
+
+obj2 = {
+  internal: {}
+};
+
+deepFreeze(obj2);
+obj2.internal.a = 'anotherValue';
+obj2.internal.a; // undefined
+ +

備註

+ +

在 ES5 中,如果傳入此方法的參數不是一個物件 (原始型別),{{jsxref("TypeError")}} 就會被丟出。而在 ES2015,一個非物件型態的參數會被當成是一個已經被凍結的物件,所以會被直接回傳?不會造成錯誤。

+ +
> Object.freeze(1)
+TypeError: 1 is not an object // ES5 code
+
+> Object.freeze(1)
+1                             // ES2015 code
+
+ +

與 Object.seal() 的差別

+ +

被 Object.seal() 密封的物件還是可以改變它原有屬性的值。而被 Object.freeze() 凍結的物件則無法改變它原有屬性的值因為他們是不可變的。

+ +

規格

+ + + + + + + + + + + + + + + + + + + + + + + + +
規格狀態備註
{{SpecName('ES5.1', '#sec-15.2.3.9', 'Object.freeze')}}{{Spec2('ES5.1')}}第一版。實作於 JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.freeze', 'Object.freeze')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.freeze', 'Object.freeze')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.Object.freeze")}}

+
+ +

參閱

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/getprototypeof/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/getprototypeof/index.html new file mode 100644 index 0000000000..ff4e4d480f --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/getprototypeof/index.html @@ -0,0 +1,128 @@ +--- +title: Object.getPrototypeOf() +slug: Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf +tags: + - JavaScript + - Method + - Object +translation_of: Web/JavaScript/Reference/Global_Objects/Object/getPrototypeOf +--- +
{{JSRef}}
+ +

Object.getPrototypeOf() 回傳指定物件的原型,換句話說,就是取得該物件的 [[Prototype]] 屬性的值).

+ +

表達式

+ +
Object.getPrototypeOf(obj)
+ +

參數

+ +
+
obj
+
欲取得原型的物件。
+
+ +

範例

+ +
var proto = {};
+var obj = Object.create(proto);
+Object.getPrototypeOf(obj) === proto; // true
+
+ +

備註

+ +

如果 obj 參數在 ES5 並不是物件時會拋出 {{jsxref("TypeError")}} 例外,同樣狀況在 ES6 時該參數將會被強制轉換成 {{jsxref("Object")}}。

+ +
Object.getPrototypeOf("foo");
+// TypeError: "foo" is not an object (ES5 code)
+Object.getPrototypeOf("foo");
+// String.prototype                  (ES6 code)
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.2', 'Object.getPrototypeOf')}}{{Spec2('ES5.1')}}Initial definition.
{{SpecName('ES6', '#sec-object.getprototypeof', 'Object.getProtoypeOf')}}{{Spec2('ES6')}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("5")}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("9")}}{{CompatOpera("12.10")}}{{CompatSafari("5")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

Opera 註

+ +

雖然舊版的 Opera 並不支援 Object.getPrototypeOf(),但是 Opera 從 Opera 10.50 支援非標準的 {{jsxref("Object.proto", "__proto__")}} 屬性。

+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/hasownproperty/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/hasownproperty/index.html new file mode 100644 index 0000000000..1786387141 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/hasownproperty/index.html @@ -0,0 +1,184 @@ +--- +title: Object.prototype.hasOwnProperty() +slug: Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty +tags: + - JavaScript +translation_of: Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty +--- +
{{JSRef}}
+ +

hasOwnProperty() 回傳物件是否有該屬性的布林值。

+ +

表達式

+ +
obj.hasOwnProperty(prop)
+ +

參數

+ +
+
prop
+
屬性名稱。
+
+ +

說明

+ +

每個為 {{jsxref("Object")}} 後代的物件都繼承 hasOwnProperty 方法。這個方法可以被使用來決定物件是否擁有特定的直接屬性;跟 {{jsxref("Operators/in", "in")}} 不一樣,這個方法並未檢查物件的原型鏈。

+ +

範例

+ +

使用 hasOwnProperty 測試屬性是否存在

+ +

這個範例顯示 o 物件是否擁有名為 prop 的屬性:

+ +
o = new Object();
+o.prop = 'exists';
+
+function changeO() {
+  o.newprop = o.prop;
+  delete o.prop;
+}
+
+o.hasOwnProperty('prop');   // 回傳 true
+changeO();
+o.hasOwnProperty('prop');   // 回傳 false
+
+ +

直接與繼承的屬性

+ +

這個範例區分直接屬性和從原型鍊繼承的屬性:

+ +
o = new Object();
+o.prop = 'exists';
+o.hasOwnProperty('prop');             // 回傳 true
+o.hasOwnProperty('toString');         // 回傳 false
+o.hasOwnProperty('hasOwnProperty');   // 回傳 false
+
+ +

遍歷物件的屬性

+ +

這個範例顯示如何不執行繼承的屬性去遍歷物件的屬性。注意 {{jsxref("Statements/for...in", "for...in")}} 已經遍歷了可以被列舉的項目,所以不該基於缺乏不可列舉的屬性(如下)而假設 hasOwnProperty 被嚴格地限制在列舉的項目(如同 {{jsxref("Object.getOwnPropertyNames()")}})。

+ +
var buz = {
+  fog: 'stack'
+};
+
+for (var name in buz) {
+  if (buz.hasOwnProperty(name)) {
+    console.log('this is fog (' + name + ') for sure. Value: ' + buz[name]);
+  }
+  else {
+    console.log(name); // toString or something else
+  }
+}
+
+ +

將 hasOwnProperty 作為屬性

+ +

JavaScript 並未保護 hasOwnProperty;因此,如果一個物件擁有一樣的屬性名稱,為了獲得正確的結果需要使用 external hasOwnProperty

+ +
var foo = {
+  hasOwnProperty: function() {
+    return false;
+  },
+  bar: 'Here be dragons'
+};
+
+foo.hasOwnProperty('bar'); // 總是回傳 false
+
+// 使用其他物件的 hasOwnProperty 和 call it with 'this' set to foo
+({}).hasOwnProperty.call(foo, 'bar'); // true
+
+// 從物件的原型使用 hasOwnProperty 也是可行的
+Object.prototype.hasOwnProperty.call(foo, 'bar'); // true
+
+ +

註:在最後一個例子中並未創建任何新的物件。

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.5.
{{SpecName('ES5.1', '#sec-15.2.4.5', 'Object.prototype.hasOwnProperty')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object.prototype.hasownproperty', 'Object.prototype.hasOwnProperty')}}{{Spec2('ES6')}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/index.html new file mode 100644 index 0000000000..3885c44a15 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/index.html @@ -0,0 +1,222 @@ +--- +title: Object +slug: Web/JavaScript/Reference/Global_Objects/Object +tags: + - Constructor + - JavaScript + - NeedsTranslation + - Object + - TopicStub +translation_of: Web/JavaScript/Reference/Global_Objects/Object +--- +
{{JSRef}}
+ +

Object 建構式可用於建立物件包裝(object wrapper)。

+ +

語法

+ +
// Object initialiser or literal
+{ [ nameValuePair1[, nameValuePair2[, ...nameValuePairN] ] ] }
+
+// Called as a constructor
+new Object([value])
+ +

參數

+ +
+
nameValuePair1, nameValuePair2, ... nameValuePairN
+
Pairs of names (strings) and values (any value) where the name is separated from the value by a colon.
+
value
+
任意值。
+
+ +

描述

+ +

The Object constructor creates an object wrapper for the given value. If the value is {{jsxref("null")}} or {{jsxref("undefined")}}, it will create and return an empty object, otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value.

+ +

When called in a non-constructor context, Object behaves identically to new Object().

+ +

也可以參考 object initializer / literal syntax.

+ +

Object 建構式屬性

+ +
+
Object.length
+
Has a value of 1.
+
{{jsxref("Object.prototype")}}
+
Allows the addition of properties to all objects of type Object.
+
+ +

Object 建構式方法

+ +
+
{{jsxref("Object.assign()")}}
+
Creates a new object by copying the values of all enumerable own properties from one or more source objects to a target object.
+
{{jsxref("Object.create()")}}
+
Creates a new object with the specified prototype object and properties.
+
{{jsxref("Object.defineProperty()")}}
+
Adds the named property described by a given descriptor to an object.
+
{{jsxref("Object.defineProperties()")}}
+
Adds the named properties described by the given descriptors to an object.
+
{{jsxref("Object.entries()")}} {{experimental_inline}}
+
Returns an array of a given object's own enumerable property [key, value] pairs.
+
{{jsxref("Object.freeze()")}}
+
Freezes an object: other code can't delete or change any properties.
+
{{jsxref("Object.getOwnPropertyDescriptor()")}}
+
Returns a property descriptor for a named property on an object.
+
{{jsxref("Object.getOwnPropertyDescriptors()")}}
+
Returns an object containing all own property descriptors for an object.
+
{{jsxref("Object.getOwnPropertyNames()")}}
+
Returns an array containing the names of all of the given object's own enumerable and non-enumerable properties.
+
{{jsxref("Object.getOwnPropertySymbols()")}}
+
Returns an array of all symbol properties found directly upon a given object.
+
{{jsxref("Object.getPrototypeOf()")}}
+
Returns the prototype of the specified object.
+
{{jsxref("Object.is()")}}
+
Compares if two values are distinguishable (ie. the same)
+
{{jsxref("Object.isExtensible()")}}
+
Determines if extending of an object is allowed.
+
{{jsxref("Object.isFrozen()")}}
+
Determines if an object was frozen.
+
{{jsxref("Object.isSealed()")}}
+
Determines if an object is sealed.
+
{{jsxref("Object.keys()")}}
+
Returns an array containing the names of all of the given object's own enumerable properties.
+
{{jsxref("Object.preventExtensions()")}}
+
Prevents any extensions of an object.
+
{{jsxref("Object.seal()")}}
+
Prevents other code from deleting properties of an object.
+
{{jsxref("Object.setPrototypeOf()")}}
+
Sets the prototype (i.e., the internal [[Prototype]] property)
+
{{jsxref("Object.values()")}} {{experimental_inline}}
+
Returns an array of a given object's own enumerable values.
+
+ +

Object 物件實體與 Object 原型物件

+ +

All objects in JavaScript are descended from Object; all objects inherit methods and properties from {{jsxref("Object.prototype")}}, although they may be overridden. For example, other constructors' prototypes override the constructor property and provide their own toString() methods. Changes to the Object prototype object are propagated to all objects unless the properties and methods subject to those changes are overridden further along the prototype chain.

+ +

屬性

+ +
{{page('/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', '屬性') }}
+ +

方法

+ +
{{page('/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype', '方法') }}
+ +

範例

+ +

Using Object given undefined and null types

+ +

下面例子儲存一個空物件至變數o

+ +
var o = new Object();
+
+ +
var o = new Object(undefined);
+
+ +
var o = new Object(null);
+
+ +

Using Object to create Boolean objects

+ +

下面例子儲存 {{jsxref("Boolean")}} 物件在 o:

+ +
// equivalent to o = new Boolean(true);
+var o = new Object(true);
+
+ +
// equivalent to o = new Boolean(false);
+var o = new Object(Boolean());
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2', 'Object')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-object-objects', 'Object')}}{{Spec2('ES6')}}Added Object.assign, Object.getOwnPropertySymbols, Object.setPrototypeOf, Object.is
{{SpecName('ESDraft', '#sec-object-objects', 'Object')}}{{Spec2('ESDraft')}}Added Object.entries, Object.values and Object.getOwnPropertyDescriptors.
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/keys/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/keys/index.html new file mode 100644 index 0000000000..958b9a3a47 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/keys/index.html @@ -0,0 +1,208 @@ +--- +title: Object.keys() +slug: Web/JavaScript/Reference/Global_Objects/Object/keys +tags: + - ECMAScript 5 + - JavaScript +translation_of: Web/JavaScript/Reference/Global_Objects/Object/keys +--- +
{{JSRef}}
+ +

Object.keys() 方法會回傳一個由指定物件所有可列舉之屬性組成的陣列,該陣列中的的排列順序與使用 {{jsxref("Statements/for...in", "for...in")}} 進行迭代的順序相同(兩者的差異在於 for-in 迴圈還會迭代出物件自其原型鏈所繼承來的可列舉屬性)。

+ +

語法

+ +
Object.keys(obj)
+ +

參數

+ +
+
obj
+
物件,用以回傳其可列舉屬性。
+
+ +

回傳值

+ +

回傳一個包含給定物件內所有可列舉屬性的字串陣列。

+ +

描述

+ +

Object.keys() 回傳一個陣列,陣列中的各元素為直屬於 obj ,對應可列舉屬性名的字串。回傳結果的排序,與手動對物件屬性作迴圈迭代的結果排序相同。

+ +

範例

+ +
var arr = ['a', 'b', 'c'];
+console.log(Object.keys(arr)); // console: ['0', '1', '2']
+
+// 類似陣列的物件
+var obj = { 0: 'a', 1: 'b', 2: 'c' };
+console.log(Object.keys(obj)); // console: ['0', '1', '2']
+
+// 擁有隨機 key 排序,類似陣列的物件
+var an_obj = { 100: 'a', 2: 'b', 7: 'c' };
+console.log(Object.keys(an_obj)); // console: ['2', '7', '100']
+
+// getFoo 不是可列舉的屬性
+var my_obj = Object.create({}, {
+  getFoo: {
+    value: function() { return this.foo; }
+  }
+});
+my_obj.foo = 1;
+
+console.log(Object.keys(my_obj)); // console: ['foo']
+
+ +

如果想取得物件的所有屬性,包括非可列舉的屬性,請參閱 {{jsxref("Object.getOwnPropertyNames()")}}.

+ +

備註

+ +

在 ES5 中,如果這個方法的參數不是一個標準物件(例如原始型別),將會產生 {{jsxref("TypeError")}}錯誤。而在 ES2015,非物件的參數將會強制轉換成物件。

+ +
Object.keys("foo");
+// TypeError: "foo" is not an object (ES5 code)
+
+Object.keys("foo");
+// ["0", "1", "2"]                   (ES2015 code)
+
+ +

Polyfill

+ +

如需在原生不支援、較舊的環境中增加 Object.keys 的相容性,請複製以下片段:

+ +
// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
+if (!Object.keys) {
+  Object.keys = (function() {
+    'use strict';
+    var hasOwnProperty = Object.prototype.hasOwnProperty,
+        hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),
+        dontEnums = [
+          'toString',
+          'toLocaleString',
+          'valueOf',
+          'hasOwnProperty',
+          'isPrototypeOf',
+          'propertyIsEnumerable',
+          'constructor'
+        ],
+        dontEnumsLength = dontEnums.length;
+
+    return function(obj) {
+      if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
+        throw new TypeError('Object.keys called on non-object');
+      }
+
+      var result = [], prop, i;
+
+      for (prop in obj) {
+        if (hasOwnProperty.call(obj, prop)) {
+          result.push(prop);
+        }
+      }
+
+      if (hasDontEnumBug) {
+        for (i = 0; i < dontEnumsLength; i++) {
+          if (hasOwnProperty.call(obj, dontEnums[i])) {
+            result.push(dontEnums[i]);
+          }
+        }
+      }
+      return result;
+    };
+  }());
+}
+
+ +

請注意以上的代碼片段在 IE7 中( IE8 也有可能 ),從不同的 window 傳入物件將包含非可列舉的 key 。

+ +

較精簡的瀏覽器 Polyfill,請參閱 Javascript - Object.keys Browser Compatibility.

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.14', 'Object.keys')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES2015', '#sec-object.keys', 'Object.keys')}}{{Spec2('ES2015')}} 
{{SpecName('ESDraft', '#sec-object.keys', 'Object.keys')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("5")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("9")}}{{CompatOpera("12")}}{{CompatSafari("5")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/preventextensions/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/preventextensions/index.html new file mode 100644 index 0000000000..bc046cf87b --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/preventextensions/index.html @@ -0,0 +1,179 @@ +--- +title: Object.preventExtensions() +slug: Web/JavaScript/Reference/Global_Objects/Object/preventExtensions +translation_of: Web/JavaScript/Reference/Global_Objects/Object/preventExtensions +--- +
{{JSRef}}
+ +

Object.preventExtensions() 用來避免物件被新增新的屬性。

+ +

語法

+ +
Object.preventExtensions(obj)
+ +

參數

+ +
+
obj
+
要被用作無法擴充的物件。
+
+ +

描述

+ +

物件如果可以被增加新的屬性,我們稱它可以被擴充(extensible)。Object.preventExtensions() 標註物件使它無法被擴充,所以在它被標註為無法擴充當下,它將無法再增加新的屬性。不過注意一點,在一般狀況下,被標註為無法擴充的物件,其屬性仍可被刪除(deleted)。嘗試去增加屬性將會導致失敗,可能會沒有結果產生,或是傳回一個 {{jsxref("TypeError")}} (最常見,但並不是一定,當在{{jsxref("Functions_and_function_scope/Strict_mode", "strict mode", "", 1)}})。

+ +

Object.preventExtensions() 只有避免物件被增加屬性,屬性仍可以被增加至 object prototype 。不過,呼叫 Object.preventExtensions() 使用在物件上,就可以使其 {{jsxref("Object.proto", "__proto__")}} {{deprecated_inline}} 屬性無法被擴充。

+ +

如果能把可擴充物件,轉成無法擴充物件,在 ECMAScript 5 規範中,它並沒有任何方法轉回來。

+ +

範例

+ +
// Object.preventExtensions 傳回一個被無法擴充的物件
+var obj = {};
+var obj2 = Object.preventExtensions(obj);
+obj === obj2; // true
+
+// 預設下,物件可以被擴充
+var empty = {};
+Object.isExtensible(empty); // === true
+
+// ...但是以下情況之後,無法再被變更。
+Object.preventExtensions(empty);
+Object.isExtensible(empty); // === false
+
+// Object.defineProperty throws 當為無法擴充的物件增加屬性
+var nonExtensible = { removable: true };
+Object.preventExtensions(nonExtensible);
+Object.defineProperty(nonExtensible, 'new', { value: 8675309 }); // throws a TypeError
+
+// 在 strict mode 中,嘗試去新增屬性給無法擴充物件,將 throws 出一個 TypeError。
+function fail() {
+  'use strict';
+  nonExtensible.newProperty = 'FAIL'; // throws a TypeError
+}
+fail();
+
+// EXTENSION (only works in engines supporting __proto__
+// (which is deprecated. Use Object.getPrototypeOf instead)):
+// A non-extensible object's prototype is immutable.
+var fixed = Object.preventExtensions({});
+fixed.__proto__ = { oh: 'hai' }; // throws a TypeError
+
+ +

筆記

+ +

在ES5中,如果給祝個方法的參數為非物件,它將造成一個 {{jsxref("TypeError")}} 。不過在 ES6 中,非物件參數會被正常處理。另外,如果它原本就是個無法擴充物件,就只是回傳本身。

+ +
Object.preventExtensions(1);
+// TypeError: 1 is not an object (ES5 code)
+
+Object.preventExtensions(1);
+// 1                             (ES6 code)
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.10', 'Object.preventExtensions')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.preventextensions', 'Object.preventExtensions')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.preventextensions', 'Object.preventExtensions')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容度

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("6")}}{{CompatGeckoDesktop("2.0")}}{{CompatIE("9")}}{{CompatOpera("12")}}{{CompatSafari("5.1")}}
ES6 behavior for non-object argument{{CompatChrome("44")}}{{CompatGeckoDesktop("35.0")}}{{CompatIE("11")}}{{CompatOpera("31")}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
ES6 behavior for non-object argument{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("35.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

閱讀更多

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/proto/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/proto/index.html new file mode 100644 index 0000000000..5ba5c8f615 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/proto/index.html @@ -0,0 +1,137 @@ +--- +title: Object.prototype.__proto__ +slug: Web/JavaScript/Reference/Global_Objects/Object/proto +translation_of: Web/JavaScript/Reference/Global_Objects/Object/proto +--- +
+

Warning: 基於現代Javascript引擎最佳化物件屬性存取的方法,改變一個物件的 [[Prototype]] 在任何瀏覽器或是Javascript引擎都是非常慢的操作?。改變繼承屬性對效能的影響微妙且深遠,不僅僅只是影響執行 obj.__proto__ = ... 的時間,而是會影響到所有有存取到被改變 [[Prototype]] 的物件的程式碼的執行時間。如果你在乎效能的話就應該避免改變一個物件的 [[Prototype]] 。反之,請用 {{jsxref("Object.create()")}} 來產生一個擁有 [[Prototype]] 的物件。

+
+ +
+

Warning: 雖然 Object.prototype.__proto__ 在今日已經被絕大部分的瀏覽器所支援,其存在與確切的行為只有在 ECMAScript 2015 規範才被標準化成一個歷史功能來確保相容性。為了更好的支援,建議使用{{jsxref("Object.getPrototypeOf()")}}。

+
+ +
{{JSRef}}
+ +

The __proto__ property of {{jsxref("Object.prototype")}} is an accessor property (a getter function and a setter function) that exposes the internal [[Prototype]] (either an object or {{jsxref("Global_Objects/null", "null")}}) of the object through which it is accessed.

+ +

The use of __proto__ is controversial, and has been discouraged. It was never originally included in the EcmaScript language spec, but modern browsers decided to implement it anyway. Only recently, the __proto__ property has been standardized in the ECMAScript 2015 language specification for web browsers to ensure compatibility, so will be supported into the future. It is deprecated in favor of {{jsxref("Object.getPrototypeOf")}}/{{jsxref("Reflect.getPrototypeOf")}} and {{jsxref("Object.setPrototypeOf")}}/{{jsxref("Reflect.setPrototypeOf")}} (though still, setting the [[Prototype]] of an object is a slow operation that should be avoided if performance is a concern).

+ +

The __proto__ property can also be used in an object literal definition to set the object [[Prototype]] on creation, as an alternative to {{jsxref("Object.create()")}}. See: object initializer / literal syntax.

+ +

Syntax

+ +
var Circle = function () {};
+var shape = {};
+var circle = new Circle();
+
+// Set the object prototype.
+// DEPRECATED. This is for example purposes only. DO NOT DO THIS in real code.
+shape.__proto__ = circle;
+
+// Get the object prototype
+console.log(shape.__proto__ === circle); // true
+
+ +
var shape = function () {};
+var p = {
+    a: function () {
+        console.log('aaa');
+    }
+};
+shape.prototype.__proto__ = p;
+
+var circle = new shape();
+circle.a(); // aaa
+console.log(shape.prototype === circle.__proto__); // true
+
+// or
+var shape = function () {};
+var p = {
+    a: function () {
+        console.log('a');
+    }
+};
+
+var circle = new shape();
+circle.__proto__ = p;
+circle.a(); // a
+console.log(shape.prototype === circle.__proto__); // false
+
+// or
+function test() {};
+test.prototype.myname = function () {
+    console.log('myname');
+};
+
+var a = new test();
+console.log(a.__proto__ === test.prototype); // true
+a.myname(); // myname
+
+
+// or
+var fn = function () {};
+fn.prototype.myname = function () {
+    console.log('myname');
+};
+
+var obj = {
+    __proto__: fn.prototype
+};
+
+obj.myname(); // myname
+
+ +

Note: that is two underscores, followed by the five characters "proto", followed by two more underscores.

+ +

Description

+ +

The __proto__ getter function exposes the value of the internal [[Prototype]] of an object. For objects created using an object literal, this value is {{jsxref("Object.prototype")}}. For objects created using array literals, this value is {{jsxref("Array.prototype")}}. For functions, this value is {{jsxref("Function.prototype")}}. For objects created using new fun, where fun is one of the built-in constructor functions provided by JavaScript ({{jsxref("Array")}}, {{jsxref("Boolean")}}, {{jsxref("Date")}}, {{jsxref("Number")}}, {{jsxref("Object")}}, {{jsxref("String")}}, and so on — including new constructors added as JavaScript evolves), this value is always fun.prototype. For objects created using new fun, where fun is a function defined in a script, this value is the value of fun.prototype. (That is, if the constructor didn't return an other object explicitly, or the fun.prototype has been reassigned since the instance was created).

+ +

The __proto__ setter allows the [[Prototype]] of an object to be mutated. The object must be extensible according to {{jsxref("Object.isExtensible()")}}: if it is not, a {{jsxref("Global_Objects/TypeError", "TypeError")}} is thrown. The value provided must be an object or {{jsxref("Global_Objects/null", "null")}}. Providing any other value will do nothing.

+ +

To understand how prototypes are used for inheritance, see guide article Inheritance and the prototype chain.

+ +

The __proto__ property is a simple accessor property on {{jsxref("Object.prototype")}} consisting of a getter and setter function. A property access for __proto__ that eventually consults {{jsxref("Object.prototype")}} will find this property, but an access that does not consult {{jsxref("Object.prototype")}} will not find it. If some other __proto__ property is found before {{jsxref("Object.prototype")}} is consulted, that property will hide the one found on {{jsxref("Object.prototype")}}.

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-additional-properties-of-the-object.prototype-object', 'Object.prototype.__proto__')}}{{Spec2('ES2015')}}Included in the (normative) annex for additional ECMAScript legacy features for Web browsers (note that the specification codifies what is already in implementations).
{{SpecName('ESDraft', '#sec-additional-properties-of-the-object.prototype-object', 'Object.prototype.__proto__')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.Object.proto")}}

+
+ +

Compatibility notes

+ +

While the ECMAScript 2015 specification dictates that support for __proto__ is required only for web browsers (although being normative), other environments may support it as well for legacy usage.

+ +

See also

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/prototype/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/prototype/index.html new file mode 100644 index 0000000000..21c2a53985 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/prototype/index.html @@ -0,0 +1,218 @@ +--- +title: Object.prototype +slug: Web/JavaScript/Reference/Global_Objects/Object/prototype +tags: + - JavaScript + - Object + - 待翻譯 +translation_of: Web/JavaScript/Reference/Global_Objects/Object +--- +
{{JSRef}}
+ +

Object.prototype 代表 {{jsxref("Object")}} 的原型物件。

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

描述

+ +

All objects in JavaScript are descended from {{jsxref("Object")}}; all objects inherit methods and properties from Object.prototype, although they may be overridden (except an Object with a null prototype, i.e. Object.create(null)). For example, other constructors' prototypes override the constructor property and provide their own {{jsxref("Object.prototype.toString()", "toString()")}} methods. Changes to the Object prototype object are propagated to all objects unless the properties and methods subject to those changes are overridden further along the prototype chain.

+ +

屬性

+ +
+
{{jsxref("Object.prototype.constructor")}}
+
Specifies the function that creates an object's prototype.
+
{{jsxref("Object.prototype.__proto__")}} {{non-standard_inline}}
+
Points to the object which was used as prototype when the object was instantiated.
+
{{jsxref("Object.prototype.__noSuchMethod__")}} {{non-standard_inline}}
+
Allows a function to be defined that will be executed when an undefined object member is called as a method.
+
{{jsxref("Object.prototype.__count__")}} {{obsolete_inline}}
+
Used to return the number of enumerable properties directly on a user-defined object, but has been removed.
+
{{jsxref("Object.prototype.__parent__")}} {{obsolete_inline}}
+
Used to point to an object's context, but has been removed.
+
+ +

方法

+ +
+
{{jsxref("Object.prototype.__defineGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Associates a function with a property that, when accessed, executes that function and returns its return value.
+
{{jsxref("Object.prototype.__defineSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Associates a function with a property that, when set, executes that function which modifies the property.
+
{{jsxref("Object.prototype.__lookupGetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Returns the function associated with the specified property by the {{jsxref("Object.defineGetter", "__defineGetter__")}} method.
+
{{jsxref("Object.prototype.__lookupSetter__()")}} {{non-standard_inline}} {{deprecated_inline}}
+
Returns the function associated with the specified property by the {{jsxref("Object.defineSetter", "__defineSetter__")}} method.
+
{{jsxref("Object.prototype.hasOwnProperty()")}}
+
Returns a boolean indicating whether an object contains the specified property as a direct property of that object and not inherited through the prototype chain.
+
{{jsxref("Object.prototype.isPrototypeOf()")}}
+
Returns a boolean indication whether the specified object is in the prototype chain of the object this method is called upon.
+
{{jsxref("Object.prototype.propertyIsEnumerable()")}}
+
Returns a boolean indicating if the internal ECMAScript DontEnum attribute is set.
+
{{jsxref("Object.prototype.toSource()")}} {{non-standard_inline}}
+
Returns string containing the source of an object literal representing the object that this method is called upon; you can use this value to create a new object.
+
{{jsxref("Object.prototype.toLocaleString()")}}
+
Calls {{jsxref("Object.toString", "toString()")}}.
+
{{jsxref("Object.prototype.toString()")}}
+
Returns a string representation of the object.
+
{{jsxref("Object.prototype.unwatch()")}} {{non-standard_inline}}
+
Removes a watchpoint from a property of the object.
+
{{jsxref("Object.prototype.valueOf()")}}
+
Returns the primitive value of the specified object.
+
{{jsxref("Object.prototype.watch()")}} {{non-standard_inline}}
+
Adds a watchpoint to a property of the object.
+
{{jsxref("Object.prototype.eval()")}} {{obsolete_inline}}
+
Used to evaluate a string of JavaScript code in the context of the specified object, but has been removed.
+
+ +

範例

+ +

因為 JavaScript 並沒有子類別的物件,所以原型是個很有用的解決辦法, 使某些函數作為物件的基本類別物件。例如:

+ +
var Person = function() {
+  this.canTalk = true;
+};
+
+Person.prototype.greet = function() {
+  if (this.canTalk) {
+    console.log('Hi, I am ' + this.name);
+  }
+};
+
+var Employee = function(name, title) {
+  Person.call(this);
+  this.name = name;
+  this.title = title;
+};
+
+Employee.prototype = Object.create(Person.prototype);
+Employee.prototype.constructor = Employee;
+
+Employee.prototype.greet = function() {
+  if (this.canTalk) {
+    console.log('Hi, I am ' + this.name + ', the ' + this.title);
+  }
+};
+
+var Customer = function(name) {
+  Person.call(this);
+  this.name = name;
+};
+
+Customer.prototype = Object.create(Person.prototype);
+Customer.prototype.constructor = Customer;
+
+var Mime = function(name) {
+  Person.call(this);
+  this.name = name;
+  this.canTalk = false;
+};
+
+Mime.prototype = Object.create(Person.prototype);
+Mime.prototype.constructor = Mime;
+
+var bob = new Employee('Bob', 'Builder');
+var joe = new Customer('Joe');
+var rg = new Employee('Red Green', 'Handyman');
+var mike = new Customer('Mike');
+var mime = new Mime('Mime');
+
+bob.greet();
+// Hi, I am Bob, the Builder
+
+joe.greet();
+// Hi, I am Joe
+
+rg.greet();
+// Hi, I am Red Green, the Handyman
+
+mike.greet();
+// Hi, I am Mike
+
+mime.greet();
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2.3.1', 'Object.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object.prototype', 'Object.prototype')}}{{Spec2('ES6')}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/object/watch/index.html b/files/zh-tw/web/javascript/reference/global_objects/object/watch/index.html new file mode 100644 index 0000000000..9dc8afa27f --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/object/watch/index.html @@ -0,0 +1,191 @@ +--- +title: Object.prototype.watch() +slug: Web/JavaScript/Reference/Global_Objects/Object/watch +translation_of: Archive/Web/JavaScript/Object.watch +--- +
{{JSRef}}
+ +
+

Warning: Generally you should avoid using watch() and {{jsxref("Object.prototype.unwatch", "unwatch()")}} when possible. These two methods are implemented only in Gecko, and they're intended primarily for debugging use. In addition, using watchpoints has a serious negative impact on performance, which is especially true when used on global objects, such as window. You can usually use setters and getters or proxies instead. See {{anch("Browser compatibility")}} for details. Also, do not confuse {{jsxref("Object.prototype.watch", "Object.watch")}} with {{jsxref("Object.prototype.observe", "Object.observe")}}.

+
+ +

The watch() method watches for a property to be assigned a value and runs a function when that occurs.

+ +

語法

+ +
obj.watch(prop, handler)
+ +

參數

+ +
+
prop
+
所需要監聽其值是否改變的物件屬性
+
handler
+
當監聽的變數其數值變換時所執行的function
+
+ +

回傳值

+ +

{{jsxref("undefined")}}.

+ +

Description

+ +

Watches for assignment to a property named prop in this object, 呼叫 handler(prop, oldval, newval) whenever prop is set and storing the return value in that property. A watchpoint can filter (or nullify) the value assignment, by returning a modified newval (or by returning oldval).

+ +

當你刪掉所監聽的物件屬性,並不會結束針對該物件屬性的監聽。當你重新產生該屬性時,監聽依舊維持作用。

+ +

要停止該次監聽, 須使用 {{jsxref("Object.unwatch", "unwatch()")}} 函式. By default, the watch method is inherited by every object descended from {{jsxref("Object")}}.

+ +

The JavaScript debugger has functionality similar to that provided by this method, as well as other debugging options. For information on the debugger, see Venkman.

+ +

In Firefox, handler is only called from assignments in script, not from native code. For example, window.watch('location', myHandler) will not call myHandler if the user clicks a link to an anchor within the current document. However, window.location += '#myAnchor' will call myHandler.

+ +
+

Note: Calling watch() on an object for a specific property overrides any previous handler attached for that property.

+
+ +

範例

+ +

使用watch 和 unwatch

+ +
var o = { p: 1 };
+
+o.watch('p', function (id, oldval, newval) {
+  console.log('o.' + id + ' changed from ' + oldval + ' to ' + newval);
+  return newval;
+});
+
+o.p = 2;
+o.p = 3;
+delete o.p;
+o.p = 4;
+
+o.unwatch('p');
+o.p = 5;
+
+ +

上述程式執行結果:

+ +
o.p changed from 1 to 2
+o.p changed from 2 to 3
+o.p changed from undefined to 4
+
+ +

使用 watch 驗證物件的屬性

+ +

You can use watch to test any assignment to an object's properties. This example ensures that every Person always has a valid name and an age between 0 and 200.

+ +
Person = function(name, age) {
+  this.watch('age', Person.prototype._isValidAssignment);
+  this.watch('name', Person.prototype._isValidAssignment);
+  this.name = name;
+  this.age = age;
+};
+
+Person.prototype.toString = function() {
+  return this.name + ', ' + this.age;
+};
+
+Person.prototype._isValidAssignment = function(id, oldval, newval) {
+  if (id === 'name' && (!newval || newval.length > 30)) {
+    throw new RangeError('invalid name for ' + this);
+  }
+  if (id === 'age'  && (newval < 0 || newval > 200)) {
+    throw new RangeError('invalid age for ' + this);
+  }
+  return newval;
+}
+
+will = new Person('Will', 29);
+console.log(will);   // Will, 29
+
+try {
+  will.name = '';
+} catch (e) {
+  console.log(e);
+}
+
+try {
+  will.age = -4;
+} catch (e) {
+  console.log(e);
+}
+
+ +

上述程式執行結果:

+ +
Will, 29
+RangeError: invalid name for Will, 29
+RangeError: invalid age for Will, 29
+
+ +

規格

+ +

Not part of any specifications. Implemented in JavaScript 1.2.

+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Compatibility notes

+ + + +

參閱

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/parseint/index.html b/files/zh-tw/web/javascript/reference/global_objects/parseint/index.html new file mode 100644 index 0000000000..ee365f3ce3 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/parseint/index.html @@ -0,0 +1,193 @@ +--- +title: parseInt() +slug: Web/JavaScript/Reference/Global_Objects/parseInt +tags: + - Global method + - parseInt + - 整數 + - 進位制 +translation_of: Web/JavaScript/Reference/Global_Objects/parseInt +--- +
{{jsSidebar("Objects")}}
+ +

parseInt() 函式能將輸入的字串轉成整數。

+ +
{{EmbedInteractiveExample("pages/js/globalprops-parseint.html")}}
+ +

語法

+ +
parseInt(string, radix);
+ +

參數

+ +
+
string
+
待轉成數字的字串。若 string 參數類型不是字串的話,會先將其轉成字串(相當於先執行 ToString 再執行 parseInt)空白值會被忽略。
+
radix
+
從 2 到 36,能代表該進位系統的數字。例如說指定 10 就等於指定十進位。一定要定義這個參數以避免他人的困惑、也好預估函式的行為。如果沒有指定 radix 的話,給出的結果會按照實做不同而異,請注意,通常預設值不是 10 進位。
+
+ +

回傳值

+ +

藉由給定字串作轉換後的數字。若第一個字符無法轉換為數字,則回傳 {{jsxref("NaN")}}。

+ +

說明

+ +

parseInt 函式會把第一個參數變成字串、解析它、再回傳整數或是 NaN。如果不是 NaN,回傳值會把第一個參數,參照指定的 radix 後,以十進位表示。例如,radix 指定為 10 的話,它會以十進位為單位轉換、8 是八進位、16 是十六進位,依此類推。For radices above 10, the letters of the alphabet indicate numerals greater than 9. For example, for hexadecimal numbers (base 16), A through F are used.

+ +

如果說 parseInt 碰上了無法被 radix 指定的進位制所轉換的字元,它會忽略該字元、以及其後所有字元,並只回傳至該位置為止的解析數值結果。parseInt 將數字擷取、轉換成整數數值。 可以接受字串首尾出現空白。

+ +

Because some numbers include the e character in their string representation (e.g. 6.022e23), using parseInt to truncate numeric values will produce unexpected results when used on very large or very small numbers. parseInt should not be used as a substitute for {{jsxref("Math.floor()")}}.

+ +

如果 radixundefined 或 0(或留空)的話,JavaScript 會:

+ + + +

如果第一個字串無法被解析為任何數字,parseInt 會回傳 NaN

+ +

For arithmetic purposes, the NaN value is not a number in any radix. You can call the {{jsxref("isNaN")}} function to determine if the result of parseInt is NaN. If NaN is passed on to arithmetic operations, the operation results will also be NaN.

+ +

若想將數字轉成特定的進位制,可使用 intValue.toString(radix)

+ +

範例

+ +

使用 parseInt

+ +

以下的範例,回傳的值均為 15

+ +
parseInt(" 0xF", 16);
+parseInt(" F", 16);
+parseInt("17", 8);
+parseInt(021, 8);
+parseInt("015", 10); // parseInt(015, 10); will return 15
+parseInt(15.99, 10);
+parseInt("15,123", 10);
+parseInt("FXX123", 16);
+parseInt("1111", 2);
+parseInt("15*3", 10);
+parseInt("15e2", 10);
+parseInt("15px", 10);
+parseInt("12", 13);
+
+ +

以下均回傳 NaN

+ +
parseInt("Hello", 8); // 根本不是數字
+parseInt("546", 2);   // 在二進位無效
+
+ +

以下的範例,回傳的值均為 -15

+ +
parseInt("-F", 16);
+parseInt("-0F", 16);
+parseInt("-0XF", 16);
+parseInt(-15.1, 10)
+parseInt(" -17", 8);
+parseInt(" -15", 10);
+parseInt("-1111", 2);
+parseInt("-15e1", 10);
+parseInt("-12", 13);
+
+ +

下例會回傳 4

+ +
parseInt(4.7, 10);
+parseInt(4.7 * 1e22, 10); // Very large number becomes 4
+parseInt(0.00000000000434, 10); // Very small number becomes 4
+
+ +

下例會回傳 224:

+ +
parseInt("0e0", 16);
+
+ +

無 radix 情況下的八進制

+ +

雖說已在 ECMAScript 3 提議並於 ECMAScript 5 禁用,但部分 javascript 編譯器仍會在特殊情況下,將 str 視作八進位數字(當數字以 0 開頭時)。以下為可能發生這種問題的情況:(永遠要宣告 radix 以避開這不可靠的行為

+ +
parseInt("0e0"); // 0
+parseInt("08"); // 0, '8' is not an octal digit.
+
+ +

ECMAScript 5 移除八進位轉譯(octal interpretation)

+ +

The ECMAScript 5 specification of the function parseInt no longer allows implementations to treat Strings beginning with a 0 character as octal values. ECMAScript 5 states:

+ +

The parseInt function produces an integer value dictated by interpretation of the contents of the string argument according to the specified radix. Leading white space in string is ignored. If radix is undefined or 0, it is assumed to be 10 except when the number begins with the character pairs 0x or 0X, in which case a radix of 16 is assumed.

+ +

This differs from ECMAScript 3, which discouraged but allowed octal interpretation.

+ +

Many implementations have not adopted this behavior as of 2013, and because older browsers must be supported, always specify a radix.

+ +

嚴謹的解析 function

+ +

有的時候,使用更嚴謹的 code 能夠更精確地轉換整數值。 Regular expressions 可以幫你:

+ +
filterInt = function (value) {
+  if(/^(\-|\+)?([0-9]+|Infinity)$/.test(value))
+    return Number(value);
+  return NaN;
+}
+
+console.log(filterInt('421'));               // 421
+console.log(filterInt('-421'));              // -421
+console.log(filterInt('+421'));              // 421
+console.log(filterInt('Infinity'));          // Infinity
+console.log(filterInt('421e+0'));            // NaN
+console.log(filterInt('421hop'));            // NaN
+console.log(filterInt('hop1.61803398875'));  // NaN
+console.log(filterInt('1.61803398875'));     // NaN
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態註解
{{SpecName('ES1')}}{{Spec2('ES1')}}初始定義
{{SpecName('ES5.1', '#sec-15.1.2.2', 'parseInt')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-parseint-string-radix', 'parseInt')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-parseint-string-radix', 'parseInt')}}{{Spec2('ESDraft')}}
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.parseInt")}}

+ +

延伸閱讀

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/promise/all/index.html b/files/zh-tw/web/javascript/reference/global_objects/promise/all/index.html new file mode 100644 index 0000000000..eb18ce63f9 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/promise/all/index.html @@ -0,0 +1,207 @@ +--- +title: Promise.all() +slug: Web/JavaScript/Reference/Global_Objects/Promise/all +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/all +--- +
{{JSRef}}
+ +

Promise.all() 方法回傳一個 {{jsxref("Promise")}} 物件,當引數 iterable 中所有的 promises 都被實現(resolved),或引數 iterable 不含任何 promise 時,被實現。或以第一個被拒絕的 promise 的原因被拒絕。

+ +

語法

+ +
Promise.all(iterable);
+ +
+
iterable
+
一個 iterable 物件像是 {{jsxref("Array")}} 或 {{jsxref("String")}}。
+
+ +

回傳值

+ + + +

描述

+ +

此方法在聚集(aggregating)多個 promises 的結果時很有幫助。

+ +

實現(Fulfillment):
+ 若傳入空的 iterable,此方法(同步地)回傳一個已被解決的 promise。若所有傳入的 promises 都被實現,或都不是 promise,Promise.all 回傳的 promise 被非同步地實現。無論是哪個情形,回傳一個以 iterable 其內所有值(包含非 promise 值)作為引數的陣列被實現。
+  

+ +

拒絕(Rejection):
+ 若任一個傳入的 promise 被拒絕,Promise.all 非同步地以其值被拒絕,無論其他 promises 是否被解決。

+ +

範例

+ +

使用 Promise.all

+ +

Promise.all 等到全部實現(或一個拒絕)。

+ +
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 陣列值(若被實現):

+ +
// 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 是空的):

+ +
// 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 被拒絕時發生一樣的事情:

+ +
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 為空:

+ +
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 將立刻被拒絕。

+ +
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"
+
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-promise.all', 'Promise.all')}}{{Spec2('ES2015')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.all', 'Promise.all')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.Promise.all")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/promise/catch/index.html b/files/zh-tw/web/javascript/reference/global_objects/promise/catch/index.html new file mode 100644 index 0000000000..d06036c11e --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/promise/catch/index.html @@ -0,0 +1,189 @@ +--- +title: Promise.prototype.catch() +slug: Web/JavaScript/Reference/Global_Objects/Promise/catch +tags: + - EMCAScript 2015 + - JavaScript + - Method + - Promise + - Prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/catch +--- +
{{JSRef}}
+ +

catch() 方法只處理 Promise 的被拒絕狀態,並回傳一個新的 Promise 物件。此方法的行為等同於呼叫 {{jsxref("Promise.then", "Promise.prototype.then(undefined, onRejected)")}}。

+ +

語法

+ +
p.catch(onRejected);
+
+p.catch(function(reason) {
+   // rejection
+});
+
+ +

參數

+ +
+
onRejected
+
一個 {{jsxref("Function")}} ,在 Promise 被拒絕時被呼叫。這個函式有一個引數: +
+
reason
+
失敗訊息。
+
+ 若 onRejected 拋出一個錯誤或回傳一個被拒絕的 Promise,則 catch() 回傳的 Promise 被拒絕;其他情形都是被實現。
+
+ +

回傳值

+ +

呼叫(catch 的 promise)物件,內部呼叫 Promise.prototype.then,傳入引數 undefined 及 onRejected;接著以之結果回傳(結果為 {{jsxref("Promise")}})。

+ +

內部呼叫演示:

+ +
// 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 方法

+ +
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');
+});
+
+ +

拋出例外時的陷阱

+ +
// 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 被實現

+ +
//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);
+});
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}{{Spec2('ES2015')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.Promise.catch")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/promise/finally/index.html b/files/zh-tw/web/javascript/reference/global_objects/promise/finally/index.html new file mode 100644 index 0000000000..eef15faf9a --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/promise/finally/index.html @@ -0,0 +1,102 @@ +--- +title: Promise.prototype.finally() +slug: Web/JavaScript/Reference/Global_Objects/Promise/finally +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/finally +--- +
{{JSRef}}
+ +

finally() 方法會回傳一個 {{jsxref("Promise")}}。當 promise 被 settled 後,無論其結果是 fulfilled 還是 rejected ,都會執行指定的回呼函數。它提供了一個讓 Promise 在被確認後,無論是 fulfilled 或是 rejected 都會執行某些程式碼的一種手段。

+ +

這樣可以避免你在 promise 的 {{jsxref("Promise.then", "then()")}} 和 {{jsxref("Promise.catch", "catch()")}} 重複處理相同的程式碼。

+ +

Syntax

+ +
p.finally(onFinally);
+
+p.finally(function() {
+   // settled(fulfilled 或 rejected)
+});
+
+ +

Parameters

+ +
+
onFinally
+
Promise settled 後呼叫的 {{jsxref("Function")}}。
+
+ +

Return value

+ +

回傳 {{jsxref("Promise")}} 當 finally 的處理函數 onFinally 被指定時。

+ +

Description

+ +

當你希望在 promise settled 後且不關心它的結果為何時,執行一些處理或清理的工作, finally() 方法會很有幫助。

+ +

finally() 方法非常類似於 .then(onFinally, onFinally) 的呼叫方式,但仍有一些差異:

+ + + +
+

備註: 在 finally 回呼中使用 throw (或回傳 rejected promise)會導致新的 promise 被 reject , reject 的原因則是呼叫 throw() 時所指定的值。

+
+ +

Examples

+ +
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; });
+
+
+ + + +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-promise.prototype.finally', 'Promise.prototype.finally')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Promise.finally")}}

+ +

See also

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/promise/index.html b/files/zh-tw/web/javascript/reference/global_objects/promise/index.html new file mode 100644 index 0000000000..8ec1456ae1 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/promise/index.html @@ -0,0 +1,256 @@ +--- +title: Promise +slug: Web/JavaScript/Reference/Global_Objects/Promise +translation_of: Web/JavaScript/Reference/Global_Objects/Promise +--- +
{{JSRef}}
+ +

Promise 物件代表一個即將完成、或失敗的非同步操作,以及它所產生的值。

+ +
+

此條目為介紹 Promise 建構式。要瞭解 Promise 相關使用方式,請先參考使用 Promise。Promise 建構式主要用於包裹尚未支援 Promise 的函式。

+
+ +
{{EmbedInteractiveExample("pages/js/promise-constructor.html")}}
+ + + + + +

語法

+ +
new Promise( /* executor */ function(resolve, reject) { ... } );
+ +

參數

+ +
+
executor
+
為一個依序接收兩個參數的函式:resolvereject(實現及拒絕回呼函式)。在 Promise 實作中,executor 函式在傳入參數 resolvereject 後會立刻執行(executor 函式會在 Promise 建構式回傳 Promise 物件前被執行)。resolvereject 函式,會在被個別呼叫時,個別執行之。通常 executor 函式會發起一些非同步操作。接著,成功完成後執行 resolve 以完成 promise;或如果有錯誤,執行 rejects
如果 executor 函式在執行中拋出錯誤,promise 會被拒絕(rejected),回傳值也將被忽略。
+
+ +

描述

+ +

Promise 會代理一個建立時,不用預先得知的值。它使你能夠繫結(associate)著發動非同步操作後,最終的成功值(success value)或失敗訊息(failure reason)的處理函式(handlers)。這讓非同步方法回傳值的方式很像同步方法,但不是回傳最終結果:非同步方法回傳一個 promise 物件作為未來某時間點的值。

+ +

一個 Promise 物件處於以下幾種狀態:

+ + + +

一個處於擱置狀態的 promise 能以一個值被實現(fulfilled),或是以一個原因或錯誤而被拒絕(rejected)。當上述任一狀態轉換發生時,那些透過 then 方法所繫結(associated)的處理函式列隊就會依序被調用。(若一個 promise 已被實現或拒絕,繫結(attached)於它的處理函式將立即被呼叫,因此完成非同步操作與繫結處理函式之間不存在競爭條件(race condition)。)

+ +

由於 {{jsxref("Promise.then", "Promise.prototype.then()")}} 以及 {{jsxref("Promise.catch", "Promise.prototype.catch()")}} 方法都回傳 promise,它們可以被串接。

+ +

+ +
+

容易混淆: 許多其他語言擁有機制用來惰性求值(lazy evaluation)及延遲(deferring)運算,它們也被稱作“promises” — e.g. Scheme. 然而在 JavaScript 中 Promises 代表那些(已經)發生中(happening)的程序,它們可以繫結回呼函式。若您要找的是惰性求值表示式,考慮不帶參數的 arrow functionf = () => expression 來建立惰性求值表示式,並透過 f() 進行求值.

+
+ +
+

Note: 一個被實現或拒絕,但不處於 pending 的 promise 被稱作被解決(settled)。您也會見到使用解決(resolved)一詞來描述 promises — 這代表 promises 被實現(fulfilled)了。States and fates 這篇文章包含了更多 promises 的專有名詞。

+
+ +

屬性

+ +
+
Promise.length
+
長度屬性,值固定為 1。(建構式參數數目).
+
{{jsxref("Promise.prototype")}}
+
Promise 建構式的原型(prototype).
+
+ +

方法

+ +
+
{{jsxref("Promise.all", "Promise.all(iterable)")}}
+
回傳一個 promise,當在引數 iterable 中所有 promises 都被實現時被實現,或在引數 iterable 中有一個 promise 被拒絕時立刻被拒絕。若回傳的 promise 被實現,它將以一個實現值的陣列被實現,其順序與 iterable 中的 promises 相同。若回傳的 promise 被拒絕,它將以失敗訊息被拒絕,此訊息來自第一個在 iterable 中被拒絕的 promise。這個方法在聚集許多 promises 的結果時很有效。
+
{{jsxref("Promise.race", "Promise.race(iterable)")}}
+
回傳一個被實現或拒絕的 promise,當 iterable 中有一個 promise 被實現或拒絕時。
+
+ +
+
{{jsxref("Promise.reject", "Promise.reject(reason)")}}
+
回傳一個以失敗訊息拒絕的 promise
+
+ +
+
{{jsxref("Promise.resolve", "Promise.resolve(value)")}}
+
回傳一個以 value 實現的 promise。若該值為 thenable (i.e. 具有 then 方法),回傳的 promise 將跟隨(follow)之,採用她的最終狀態; 在其他情形回傳的 promise 將以 value 被實現。一般來說,當您不知道 value 是否為 promise,使用 {{jsxref("Promise.resolve", "Promise.resolve(value)")}},將回傳值以 promise 作處理。
+
+ +

Promise 原型

+ +

屬性

+ +

{{page('zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Promise/prototype','屬性')}}

+ +

方法

+ +

{{page('zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Promise/prototype','方法')}}

+ +

建立 Promise

+ +

一個 Promise 物件透過 new 及其建構式建立。這個建構式接收一個叫作”執行器函式(executor function)“的引數。此函式接收兩個函式作為引數。第一個函式(resolve)在非同步作業成功完成時,以該作業之結果值被呼叫。第二個函式(reject)在作業失敗時,以失敗訊息,通常是一個 error object,被呼叫。

+ +
const myFirstPromise = new Promise((resolve, reject) => {
+  // 執行一些非同步作業,最終呼叫:
+  //
+  //   resolve(someValue); // 實現
+  // 或
+  //   reject("failure reason"); // 拒絕
+});
+
+ +

要提供一個函式 promise 功能,讓它回傳一個 promise 即可:

+ +
function myAsyncFunction(url) {
+  return new Promise((resolve, reject) => {
+    const xhr = new XMLHttpRequest();
+    xhr.open("GET", url);
+    xhr.onload = () => resolve(xhr.responseText);
+    xhr.onerror = () => reject(xhr.statusText);
+    xhr.send();
+  });
+};
+ +

範例

+ +

入門範例

+ +
let myFirstPromise = new Promise((resolve, reject) => {
+  // 當非同步作業成功時,呼叫 resolve(...),而失敗時則呼叫 reject(...)。
+  // 在這個例子中,使用 setTimeout(...) 來模擬非同步程式碼。
+  // 在實務中,您將可能使用像是 XHR 或者一個 HTML5 API.
+  setTimeout(function(){
+    resolve("Success!"); // Yay!非常順利!
+  }, 250);
+});
+
+myFirstPromise.then((successMessage) => {
+  // successMessage 是任何您由上方 resolve(...) 傳入的東西。
+  // 在此僅作為成功訊息,但是它不一定是字串。
+  console.log("Yay! " + successMessage);
+});
+
+ +

進階範例

+ + + +

這個小範例演示了 Promise 的運作機制。每當 {{HTMLElement("button")}} 被點擊時,testPromise() 方法被呼叫。每次點擊將透過 {{domxref("window.setTimeout()")}} 建立一個將在 1-3 秒內隨機地被實現的 promise,供 promise 計數(一個從 1 開始的數值)。建構式 Promise() 被用來建立 promise。

+ +

promise 的實現值單純地經由一個實現回呼函式 {{jsxref("Promise.prototype.then()","p1.then()")}} 被印出。下以一些文字紀錄來展現方法中同步的與非同步處理 promise 的部分是如何分離彼此。

+ +
'use strict';
+var promiseCount = 0;
+
+function testPromise() {
+    let thisPromiseCount = ++promiseCount;
+
+    let log = document.getElementById('log');
+    log.insertAdjacentHTML('beforeend', thisPromiseCount +
+        ') Started (<small>Sync code started</small>)<br/>');
+
+    // 建立一個新的 promise:此 promise 承諾一個數值計數, 由 1 開始(等待約 2 秒)
+    let p1 = new Promise(
+        // 這個解決器函數(resolver function)呼叫實現或
+        // 拒絕 promise。
+        (resolve, reject) => {
+            log.insertAdjacentHTML('beforeend', thisPromiseCount +
+                ') Promise started (<small>Async code started</small>)<br/>');
+            // 在此例子單純用來產生非同步特性。
+            window.setTimeout(
+                function() {
+                    // 實現這個 promise!
+                    resolve(thisPromiseCount);
+                }, Math.random() * 2000 + 1000);
+        }
+    );
+
+    // 接著透過呼叫 then() 來決定 promise 進入 resolved 時,要透過 then() 做什麼,
+    // 或是進入 rejected 時,要透過 catch() 方法要做什麼。
+    p1.then(
+        // 印出實現值(fulfillment value)
+        function(val) {
+            log.insertAdjacentHTML('beforeend', val +
+                ') Promise fulfilled (<small>Async code terminated</small>)<br/>');
+        })
+    .catch(
+        // 印出失敗訊息(rejection reason)
+        (reason) => {
+            console.log('Handle rejected promise ('+reason+') here.');
+        });
+
+    log.insertAdjacentHTML('beforeend', thisPromiseCount +
+        ') Promise made (<small>Sync code terminated</small>)<br/>');
+}
+ +

*譯註:resolver function 即 executor function。

+ + + +

這個範例從點擊按鈕開始。您的瀏覽器需要支援 Promise。在短時間內點擊按鈕許多次,您甚至將看到不同的 promises 一個接一個地被實現。

+ +

{{EmbedLiveSample("Advanced_Example", "500", "200")}}

+ +

使用 XHR 載入圖片

+ +

另一個使用 Promise and XMLHttpRequest 來載入圖片的簡單例子可以在 MDN GitHub js-examples 儲存庫找到。 你也可以see it in action。每個步驟都附以註解,讓你能逐步遵隨 Promise 與 XHR 架構。

+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-promise-objects', 'Promise')}}{{Spec2('ES2015')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise-objects', 'Promise')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.Promise")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/promise/prototype/index.html b/files/zh-tw/web/javascript/reference/global_objects/promise/prototype/index.html new file mode 100644 index 0000000000..476c52f7a3 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/promise/prototype/index.html @@ -0,0 +1,64 @@ +--- +title: Promise.prototype +slug: Web/JavaScript/Reference/Global_Objects/Promise/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/Promise +--- +
{{JSRef}}
+ +

Promise.prototype 屬性代表了 {{jsxref("Promise")}} 建構式的原型物件。

+ +
{{js_property_attributes(0,0,0)}}
+ +

描述

+ +

所有 {{jsxref("Promise")}} 實例都繼承自 {{jsxref("Promise.prototype")}}。您可以使用建構式的原型物件來增加屬性或方法到所有的 Promise 實例。

+ +

屬性

+ +
+
Promise.prototype.constructor
+
回傳一個建立實例原型(instance's prototype)的函式。預設為 {{jsxref("Promise")}} 函數。
+
+ +

方法

+ +
+
{{jsxref("Promise.catch", "Promise.prototype.catch(onRejected)")}}
+
繫結一個拒絕回呼函式(rejection handler callback)到 promise,當它被呼叫時回傳一個以回傳值作解析的新 promise,或者當 promise 被實現時以原值作解析。
+
{{jsxref("Promise.then", "Promise.prototype.then(onFulfilled, onRejected)")}}
+
繫結實現或拒絕回呼函式到 promise,回傳一個以 handler 之回傳值作解析的新 promise,或者當 promise 未處理(not handled)時以原值作解析。(i.e. 比如相關聯的 onFulfilled 或 onRejected 不是函式。)
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES6', '#sec-promise.prototype', 'Promise.prototype')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-promise.prototype', 'Promise.prototype')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript/promise","Promise.prototype")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/promise/race/index.html b/files/zh-tw/web/javascript/reference/global_objects/promise/race/index.html new file mode 100644 index 0000000000..9f0d8b4d2e --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/promise/race/index.html @@ -0,0 +1,171 @@ +--- +title: Promise.race() +slug: Web/JavaScript/Reference/Global_Objects/Promise/race +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/race +--- +
{{JSRef}}
+ +

Promise.race(iterable) 方法回傳一個 promise 物件,此 promise 物件會於 iterable 引數中任一個 promise 轉為 resolve 或 rejected 時立即轉變成 resolve 或 rejected,並且接收其成功值或失敗訊息。

+ +

語法

+ +
Promise.race(iterable);
+ +

參數

+ +
+
iterable
+
一個 iterable 物件,像是 {{jsxref("Array")}}. 請參考可迭代協議
+
+ +

回傳值

+ +

當傳入的 iterable 中有 promise 被實現或拒絕時,立刻回傳被實現或拒絕的 {{jsxref("Promise")}}。

+ +

描述

+ +

race 函式回傳一個與傳入的 iterable 之中第一個被解決(settled)的 promise 相同方式被解決(且以相同值)的 Promise

+ +

範例

+ +

Promise.race 的非同步性質

+ +

以下例子演示了 Promise.race 的非同步性質:

+ +
// 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 永久擱置:

+ +
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 將以陣列中第一個這樣的值解決:

+ +
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 的範例

+ +
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
+});
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-promise.race', 'Promise.race')}}{{Spec2('ES2015')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.race', 'Promise.race')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.Promise.race")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/promise/reject/index.html b/files/zh-tw/web/javascript/reference/global_objects/promise/reject/index.html new file mode 100644 index 0000000000..0c41a37509 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/promise/reject/index.html @@ -0,0 +1,72 @@ +--- +title: Promise.reject() +slug: Web/JavaScript/Reference/Global_Objects/Promise/reject +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/reject +--- +
{{JSRef}}
+ +

Promise.reject(reason) 方法回傳一個以 reason 拒絕的 Promise 物件。

+ +

語法

+ +
Promise.reject(reason);
+ +

參數

+ +
+
reason
+
Promise 的失敗訊息。
+
+ +

回傳值

+ +

一個以 reason 拒絕的 {{jsxref("Promise")}}。

+ +

描述

+ +

靜態函式 Promise.reject 回傳一個被拒絕的 Promise。由於除錯目的及選擇性錯誤捕捉(selective error catching),使用一個 instanceof {{jsxref("Error")}} 作為 reason 是很有幫助的。

+ +

範例

+ +

使用靜態方法 Promise.reject()

+ +
Promise.reject(new Error('fail')).then(function(error) {
+  // not called
+}, function(error) {
+  console.log(error); // Stacktrace
+});
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-promise.reject', 'Promise.reject')}}{{Spec2('ES2015')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.reject', 'Promise.reject')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.Promise.reject")}}

+ +

See also

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/promise/resolve/index.html b/files/zh-tw/web/javascript/reference/global_objects/promise/resolve/index.html new file mode 100644 index 0000000000..e2d460a7e3 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/promise/resolve/index.html @@ -0,0 +1,142 @@ +--- +title: Promise.resolve() +slug: Web/JavaScript/Reference/Global_Objects/Promise/resolve +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/resolve +--- +
{{JSRef}}
+ +

Promise.resolve(value) 方法回傳一個以 value 判定結果的 {{jsxref("Promise")}} 物件。若 value 是個 thenable (例如,具有 {{jsxref("Promise.then", "\"then\"方法")}}),則回傳的 promise 將依其結果採取其最終狀態;若 value 是 promise,則作為呼叫 Promise.resolve 之結果;其他情形都將回傳以 value 實現的 promise。

+ +

語法

+ +
Promise.resolve(value);
+Promise.resolve(promise);
+Promise.resolve(thenable);
+
+ +

參數

+ +
+
value
+
將被 Promise 實現的引數(argument)。可以是個 Promise 或待解決的 thenable。
+
+ +

回傳值

+ +

以 value 或作為 value 的 promise 解決的 {{jsxref("Promise")}}。

+ +

描述

+ +

靜態函式 Promise.resolve 回傳判定後的 Promise。

+ +

範例

+ +

使用 Promise.resolve 靜態方法

+ +
Promise.resolve('Success').then(function(value) {
+  console.log(value); // "Success"
+}, function(value) {
+  // not called
+});
+
+ +

判定陣列

+ +
var p = Promise.resolve([1,2,3]);
+p.then(function(v) {
+  console.log(v[0]); // 1
+});
+
+ +

判定另一個 Promise

+ +
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
+
+ +

由於 handlers 是非同步地被調用而導致相反的紀錄順序。經由這篇文章了解 then 如何運作。

+ +

判定 thenables 及拋出 Errors

+ +
// 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
+});
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-promise.resolve', 'Promise.resolve')}}{{Spec2('ES2015')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.resolve', 'Promise.resolve')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.Promise.resolve")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/promise/then/index.html b/files/zh-tw/web/javascript/reference/global_objects/promise/then/index.html new file mode 100644 index 0000000000..19682d0199 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/promise/then/index.html @@ -0,0 +1,271 @@ +--- +title: Promise.prototype.then() +slug: Web/JavaScript/Reference/Global_Objects/Promise/then +translation_of: Web/JavaScript/Reference/Global_Objects/Promise/then +--- +
{{JSRef}}
+ +

then() 方法回傳一個 {{domxref("Promise")}} 物件。它接收兩個引數: Promise 在成功及失敗情況時的回呼函式。

+ +
+

如果有一個或兩個引數被省略,或為非函式(non-functions),則 then 將處於遺失 handler(s) 的狀態,但不會產生錯誤。若發起 then 之 Promise 採取了一個狀態(實現(fulfillment)或拒絕(rejection))而 then 沒有處理它的函式,一個不具有額外 handlers 的新 Promise 物件將被建立,單純採取原 Promise 其最終狀態。

+
+ +

語法

+ +
p.then(onFulfilled[, onRejected]);
+
+p.then(function(value) {
+  // fulfillment
+}, function(reason) {
+  // rejection
+});
+
+ +

參數

+ +
+
onFulfilled
+
一個 {{jsxref("Function")}},當 Promise 被實現(fulfilled)時被呼叫。此函式接收一個實現值(fullfillment value)作為引數。
+
onRejected {{optional_inline}}
+
一個 {{jsxref("Function")}},當 Promise 被拒絕(rejected)時被呼叫。此函式接收一個失敗訊息(rejection reason)作為引數。
+
+ +

回傳值

+ +

一個進入擱置(pending)狀態的 {{jsxref("Promise")}}。(只要堆疊一空)handler 函式非同步地(asynchronously)被呼叫。在調用 handler 後,若 handler 函式:

+ + + +

以下例子展示 then 方法的非同步性質(asynchronicity)。

+ +
// 使用一個已實現的 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 和 {{jsxref("Promise.prototype.catch()")}} 方法都回傳 promises,它們可以被串接 — 稱為組合(composition)。

+ +

範例

+ +

運用 then 方法

+ +
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 函式模擬非同步程式碼。

+ +
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>).

+ +
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。

+ +
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 被否決。

+ +
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 語法,如下展示。

+ +
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 函式,基於它本身。

+ +
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 的實現/否決將取決它。

+ +
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
+});
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-promise.prototype.then', 'Promise.prototype.then')}}{{Spec2('ES2015')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.prototype.then', 'Promise.prototype.then')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript/promise","Promise.prototype.then")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/proxy/index.html b/files/zh-tw/web/javascript/reference/global_objects/proxy/index.html new file mode 100644 index 0000000000..54a71be888 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/proxy/index.html @@ -0,0 +1,400 @@ +--- +title: Proxy +slug: Web/JavaScript/Reference/Global_Objects/Proxy +tags: + - Class + - ECMAScript 2015 + - JavaScript + - Proxy +translation_of: Web/JavaScript/Reference/Global_Objects/Proxy +--- +
+
{{JSRef}}
+
+ +

Proxy 物件被使用於定義基本操作的自定行為(例如:尋找屬性、賦值、列舉、函式調用等等)。

+ +

術語

+ +
+
handler
+
Placeholder object which contains traps.
+
traps
+
The methods that provide property access. This is analogous to the concept of traps in operating systems.
+
target
+
Object which the proxy virtualizes. It is often used as storage backend for the proxy. Invariants (semantics that remain unchanged) regarding object non-extensibility or non-configurable properties are verified against the target.
+
+ +

語法

+ +
var p = new Proxy(target, handler);
+
+ +

參數

+ +
+
target
+
A target object (can be any sort of object, including a native array, a function or even another proxy) to wrap with Proxy.
+
handler
+
An object whose properties are functions which define the behavior of the proxy when an operation is performed on it.
+
+ +

方法

+ +
+
{{jsxref("Proxy.revocable()")}}
+
Creates a revocable Proxy object.
+
+ +

Methods of the handler object

+ +

The handler object is a placeholder object which contains traps for Proxy.

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler', 'Methods') }}
+ +

範例

+ +

Basic example

+ +

In this simple example the number 37 gets returned as the default value when the property name is not in the object. It is using the get handler.

+ +
var handler = {
+    get: function(target, name) {
+        return name in target ?
+            target[name] :
+            37;
+    }
+};
+
+var p = new Proxy({}, handler);
+p.a = 1;
+p.b = undefined;
+
+console.log(p.a, p.b); // 1, undefined
+console.log('c' in p, p.c); // false, 37
+
+ +

No-op forwarding proxy

+ +

In this example, we are using a native JavaScript object to which our proxy will forward all operations that are applied to it.

+ +
var target = {};
+var p = new Proxy(target, {});
+
+p.a = 37; // operation forwarded to the target
+
+console.log(target.a); // 37. The operation has been properly forwarded
+
+ +

Validation

+ +

With a Proxy, you can easily validate the passed value for an object. This example uses the set handler.

+ +
let validator = {
+  set: function(obj, prop, value) {
+    if (prop === 'age') {
+      if (!Number.isInteger(value)) {
+        throw new TypeError('The age is not an integer');
+      }
+      if (value > 200) {
+        throw new RangeError('The age seems invalid');
+      }
+    }
+
+    // The default behavior to store the value
+    obj[prop] = value;
+
+    // Indicate success
+    return true;
+  }
+};
+
+let person = new Proxy({}, validator);
+
+person.age = 100;
+console.log(person.age); // 100
+person.age = 'young'; // Throws an exception
+person.age = 300; // Throws an exception
+ +

Extending constructor

+ +

A function proxy could easily extend a constructor with a new constructor. This example uses the construct and apply handlers.

+ +
function extend(sup, base) {
+  var descriptor = Object.getOwnPropertyDescriptor(
+    base.prototype, 'constructor'
+  );
+  base.prototype = Object.create(sup.prototype);
+  var handler = {
+    construct: function(target, args) {
+      var obj = Object.create(base.prototype);
+      this.apply(target, obj, args);
+      return obj;
+    },
+    apply: function(target, that, args) {
+      sup.apply(that, args);
+      base.apply(that, args);
+    }
+  };
+  var proxy = new Proxy(base, handler);
+  descriptor.value = proxy;
+  Object.defineProperty(base.prototype, 'constructor', descriptor);
+  return proxy;
+}
+
+var Person = function(name) {
+  this.name = name;
+};
+
+var Boy = extend(Person, function(name, age) {
+  this.age = age;
+});
+
+Boy.prototype.sex = 'M';
+
+var Peter = new Boy('Peter', 13);
+console.log(Peter.sex);  // "M"
+console.log(Peter.name); // "Peter"
+console.log(Peter.age);  // 13
+ +

Manipulating DOM nodes

+ +

Sometimes you want to toggle the attribute or class name of two different elements. Here's how using the set handler.

+ +
let view = new Proxy({
+  selected: null
+},
+{
+  set: function(obj, prop, newval) {
+    let oldval = obj[prop];
+
+    if (prop === 'selected') {
+      if (oldval) {
+        oldval.setAttribute('aria-selected', 'false');
+      }
+      if (newval) {
+        newval.setAttribute('aria-selected', 'true');
+      }
+    }
+
+    // The default behavior to store the value
+    obj[prop] = newval;
+
+    // Indicate success
+    return true;
+  }
+});
+
+let i1 = view.selected = document.getElementById('item-1');
+console.log(i1.getAttribute('aria-selected')); // 'true'
+
+let i2 = view.selected = document.getElementById('item-2');
+console.log(i1.getAttribute('aria-selected')); // 'false'
+console.log(i2.getAttribute('aria-selected')); // 'true'
+ +

Value correction and an extra property

+ +

The products proxy object evaluates the passed value and convert it to an array if needed. The object also supports an extra property called latestBrowser both as a getter and a setter.

+ +
let products = new Proxy({
+  browsers: ['Internet Explorer', 'Netscape']
+},
+{
+  get: function(obj, prop) {
+    // An extra property
+    if (prop === 'latestBrowser') {
+      return obj.browsers[obj.browsers.length - 1];
+    }
+
+    // The default behavior to return the value
+    return obj[prop];
+  },
+  set: function(obj, prop, value) {
+    // An extra property
+    if (prop === 'latestBrowser') {
+      obj.browsers.push(value);
+      return true;
+    }
+
+    // Convert the value if it is not an array
+    if (typeof value === 'string') {
+      value = [value];
+    }
+
+    // The default behavior to store the value
+    obj[prop] = value;
+
+    // Indicate success
+    return true;
+  }
+});
+
+console.log(products.browsers); // ['Internet Explorer', 'Netscape']
+products.browsers = 'Firefox'; // pass a string (by mistake)
+console.log(products.browsers); // ['Firefox'] <- no problem, the value is an array
+
+products.latestBrowser = 'Chrome';
+console.log(products.browsers); // ['Firefox', 'Chrome']
+console.log(products.latestBrowser); // 'Chrome'
+ +

Finding an array item object by its property

+ +

This proxy extends an array with some utility features. As you see, you can flexibly "define" properties without using Object.defineProperties. This example can be adapted to find a table row by its cell. In that case, the target will be table.rows.

+ +
let products = new Proxy([
+  { name: 'Firefox', type: 'browser' },
+  { name: 'SeaMonkey', type: 'browser' },
+  { name: 'Thunderbird', type: 'mailer' }
+],
+{
+  get: function(obj, prop) {
+    // The default behavior to return the value; prop is usually an integer
+    if (prop in obj) {
+      return obj[prop];
+    }
+
+    // Get the number of products; an alias of products.length
+    if (prop === 'number') {
+      return obj.length;
+    }
+
+    let result, types = {};
+
+    for (let product of obj) {
+      if (product.name === prop) {
+        result = product;
+      }
+      if (types[product.type]) {
+        types[product.type].push(product);
+      } else {
+        types[product.type] = [product];
+      }
+    }
+
+    // Get a product by name
+    if (result) {
+      return result;
+    }
+
+    // Get products by type
+    if (prop in types) {
+      return types[prop];
+    }
+
+    // Get product types
+    if (prop === 'types') {
+      return Object.keys(types);
+    }
+
+    return undefined;
+  }
+});
+
+console.log(products[0]); // { name: 'Firefox', type: 'browser' }
+console.log(products['Firefox']); // { name: 'Firefox', type: 'browser' }
+console.log(products['Chrome']); // undefined
+console.log(products.browser); // [{ name: 'Firefox', type: 'browser' }, { name: 'SeaMonkey', type: 'browser' }]
+console.log(products.types); // ['browser', 'mailer']
+console.log(products.number); // 3
+
+ +

A complete traps list example

+ +

Now in order to create a complete sample traps list, for didactic purposes, we will try to proxify a non native object that is particularly suited to this type of operation: the docCookies global object created by the "little framework" published on the document.cookie page.

+ +
/*
+  var docCookies = ... get the "docCookies" object here:
+  https://developer.mozilla.org/en-US/docs/DOM/document.cookie#A_little_framework.3A_a_complete_cookies_reader.2Fwriter_with_full_unicode_support
+*/
+
+var docCookies = new Proxy(docCookies, {
+  get: function (oTarget, sKey) {
+    return oTarget[sKey] || oTarget.getItem(sKey) || undefined;
+  },
+  set: function (oTarget, sKey, vValue) {
+    if (sKey in oTarget) { return false; }
+    return oTarget.setItem(sKey, vValue);
+  },
+  deleteProperty: function (oTarget, sKey) {
+    if (sKey in oTarget) { return false; }
+    return oTarget.removeItem(sKey);
+  },
+  enumerate: function (oTarget, sKey) {
+    return oTarget.keys();
+  },
+  ownKeys: function (oTarget, sKey) {
+    return oTarget.keys();
+  },
+  has: function (oTarget, sKey) {
+    return sKey in oTarget || oTarget.hasItem(sKey);
+  },
+  defineProperty: function (oTarget, sKey, oDesc) {
+    if (oDesc && 'value' in oDesc) { oTarget.setItem(sKey, oDesc.value); }
+    return oTarget;
+  },
+  getOwnPropertyDescriptor: function (oTarget, sKey) {
+    var vValue = oTarget.getItem(sKey);
+    return vValue ? {
+      value: vValue,
+      writable: true,
+      enumerable: true,
+      configurable: false
+    } : undefined;
+  },
+});
+
+/* Cookies test */
+
+console.log(docCookies.my_cookie1 = 'First value');
+console.log(docCookies.getItem('my_cookie1'));
+
+docCookies.setItem('my_cookie1', 'Changed value');
+console.log(docCookies.my_cookie1);
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-proxy-objects', 'Proxy')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-proxy-objects', 'Proxy')}}{{Spec2('ESDraft')}}
+ +

瀏覽器相容性

+ +

{{Compat("javascript.builtins.Proxy", 2)}}

+ +

Gecko specific notes

+ + + +

參見

+ + + +

Licensing note

+ +

Some content (text, examples) in this page has been copied or adapted from the ECMAScript wiki which content is licensed CC 2.0 BY-NC-SA.

diff --git a/files/zh-tw/web/javascript/reference/global_objects/rangeerror/index.html b/files/zh-tw/web/javascript/reference/global_objects/rangeerror/index.html new file mode 100644 index 0000000000..257c23be9a --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/rangeerror/index.html @@ -0,0 +1,152 @@ +--- +title: RangeError +slug: Web/JavaScript/Reference/Global_Objects/RangeError +tags: + - Error + - JavaScript + - Object + - RangeError +translation_of: Web/JavaScript/Reference/Global_Objects/RangeError +--- +
{{JSRef}}
+ +

RangeError物件在一個給定的值不在允許的集合或範圍內時被作為一個錯誤拋出

+ +

語法

+ +
new RangeError([message[, fileName[, lineNumber]]])
+ +

參數

+ +
+
message
+
可選。具人類可讀性的錯誤說明
+
fileName {{non-standard_inline}}
+
可選。包含造成錯誤發生的程式碼的檔案名稱
+
lineNumber {{non-standard_inline}}
+
可選。造成錯誤發生的程式碼行號
+
+ +

說明

+ +

當試著往一個 function 傳入一個不被其允許的值作為參數時,一個RangeError被拋出。這可在多種情況遭遇到,例如傳入一個不被允許的字串值到 {{jsxref("String.prototype.normalize()")}},或試著透過 {{jsxref("Array")}} constructor 用一個不合法的長度來創建一個陣列,或往數值方法像是{{jsxref("Number.toExponential()")}}、{{jsxref("Number.toFixed()")}}、{{jsxref("Number.toPrecision()")}} 傳進糟糕的值。

+ +

屬性

+ +
+
{{jsxref("RangeError.prototype")}}
+
允許對一個 RangeError 物件增加其屬性。
+
+ +

方法

+ +

普遍的 RangeError 自身沒有包含方法,儘管他的確從原型鍊中繼承了一些。

+ +

RangeError 物件實體

+ +

屬性

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError/prototype', 'Properties')}}
+ +

方法

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError/prototype', 'Methods')}}
+ +

範例

+ +

使用 RangeError (數值)

+ +
function check(n)
+{
+    if(!(n >= -500 && n <= 500))
+    {
+        throw new RangeError("The argument must be between -500 and 500.");
+    }
+}
+
+try
+{
+    check(2000);
+}
+catch(error)
+{
+    if(error instanceof RangeError)
+    {
+        // Handle the error.
+    }
+}
+ +

使用 RangeError (非數值)

+ +
function check(value)
+{
+    if(["apple", "banana", "carrot"].includes(value) === false)
+    {
+        throw new RangeError("The argument must be an \"apple\", \"banana\", or \"carrot\".");
+    }
+}
+
+try
+{
+    check("cabbage");
+}
+catch(error)
+{
+    if(error instanceof RangeError)
+    {
+        // Handle the error.
+    }
+}
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態注解
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.11.6.2', 'RangeError')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-native-error-types-used-in-this-standard-rangeerror', 'RangeError')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-native-error-types-used-in-this-standard-rangeerror', 'RangeError')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.RangeError")}}

+
+ +

另見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/reflect/index.html b/files/zh-tw/web/javascript/reference/global_objects/reflect/index.html new file mode 100644 index 0000000000..4f1d980a0d --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/reflect/index.html @@ -0,0 +1,130 @@ +--- +title: Reflect +slug: Web/JavaScript/Reference/Global_Objects/Reflect +translation_of: Web/JavaScript/Reference/Global_Objects/Reflect +--- +
{{JSRef}}
+ +

Reflect 是一個內建物件,提供了用於獲取可截取之 JavaScript 操作的方法。這些方法與 proxy handlers 的方法相同。Reflect 不是一個函式物件,因此它是不可建構的。

+ +

描述

+ +

Unlike most global objects, Reflect is not a constructor. You can not use it with a new operator or invoke the Reflect object as a function. All properties and methods of Reflect are static (just like the {{jsxref("Math")}} object).

+ +

方法

+ +

The Reflect object provides the following static functions which have the same names as the proxy handler methods. Some of these methods are the same as corresponding methods on {{jsxref("Object")}}.

+ +
+
{{jsxref("Reflect.apply()")}}
+
Calls a target function with arguments as specified by the args parameter. See also {{jsxref("Function.prototype.apply()")}}.
+
{{jsxref("Reflect.construct()")}}
+
 The new operator as a function. Equivalent to calling new target(...args).
+
{{jsxref("Reflect.defineProperty()")}}
+
Similar to {{jsxref("Object.defineProperty()")}}. Returns a {{jsxref("Boolean")}}.
+
{{jsxref("Reflect.deleteProperty()")}}
+
The delete operator as a function. Equivalent to calling delete target[name].
+
{{jsxref("Reflect.get()")}}
+
A function that returns the value of properties.
+
{{jsxref("Reflect.getOwnPropertyDescriptor()")}}
+
Similar to {{jsxref("Object.getOwnPropertyDescriptor()")}}. Returns a property descriptor of the given property if it exists on the object,  {{jsxref("undefined")}} otherwise.
+
{{jsxref("Reflect.getPrototypeOf()")}}
+
Same as {{jsxref("Object.getPrototypeOf()")}}.
+
{{jsxref("Reflect.has()")}}
+
The in operator as function. Returns a boolean indicating whether an own or inherited property exists.
+
{{jsxref("Reflect.isExtensible()")}}
+
Same as {{jsxref("Object.isExtensible()")}}.
+
{{jsxref("Reflect.ownKeys()")}}
+
Returns an array of the target object's own (not inherited) property keys.
+
{{jsxref("Reflect.preventExtensions()")}}
+
Similar to {{jsxref("Object.preventExtensions()")}}. Returns a {{jsxref("Boolean")}}.
+
{{jsxref("Reflect.set()")}}
+
A function that assigns values to properties. Returns a {{jsxref("Boolean")}} that is true if the update was successful.
+
{{jsxref("Reflect.setPrototypeOf()")}}
+
A function that sets the prototype of an object.
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-reflect-object', 'Reflect')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-reflect-object', 'Reflect')}}{{Spec2('ESDraft')}}Reflect.enumerate has been removed.
+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(49.0)}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("42")}}{{CompatNo}}{{CompatNo}}{{CompatSafari(10)}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatChrome(49.0)}}{{CompatChrome(49.0)}}{{CompatVersionUnknown}}{{CompatGeckoMobile("42")}}{{CompatNo}}{{CompatNo}}{{CompatSafari(10)}}
+
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/regexp/index.html b/files/zh-tw/web/javascript/reference/global_objects/regexp/index.html new file mode 100644 index 0000000000..7bf77316e2 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/regexp/index.html @@ -0,0 +1,269 @@ +--- +title: RegExp +slug: Web/JavaScript/Reference/Global_Objects/RegExp +translation_of: Web/JavaScript/Reference/Global_Objects/RegExp +--- +
{{JSRef}}
+ +
+ +

RegExp 物件被用來比對符合自訂規則的文字。

+ +

關於正規表達式(regular expressions)的介紹,可以閱讀 JavaScript 指南中的 正規表達式章節

+ +

說明

+ +

建立 RegExp 物件有兩種方式:文字表示法 (literal notation) 和 建構子 (constructor)。

+ + + +

以下的表達式會建立出相同的正規表達式:

+ +
/ab+c/i
+new RegExp(/ab+c/, 'i') // literal notation
+new RegExp('ab+c', 'i') // constructor
+
+ +

The literal notation provides a compilation of the regular expression when the expression is evaluated. Use literal notation when the regular expression will remain constant. For example, if you use literal notation to construct a regular expression used in a loop, the regular expression won't be recompiled on each iteration.

+ +

The constructor of the regular expression object—for example, new RegExp('ab+c')—provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.

+ +

Starting with ECMAScript 6, new RegExp(/ab+c/, 'i') no longer throws a {{jsxref("TypeError")}} ("can't supply flags when constructing one RegExp from another") when the first argument is a RegExp and the second flags argument is present. A new RegExp from the arguments is created instead.

+ +

When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary.

+ +

For example, the following are equivalent:

+ +
let re = /\w+/
+let re = new RegExp('\\w+')
+
+ +

Constructor

+ +
+
RegExp()
+
Creates a regular expression object.
+
+ +

Properties

+ +
+
RegExp.prototype
+
Allows the addition of properties to all objects.
+
RegExp.length
+
The value of RegExp.length is 2.
+
{{jsxref("RegExp.@@species", "get RegExp[@@species]")}}
+
The constructor function that is used to create derived objects.
+
{{jsxref("RegExp.lastIndex")}}
+
The index at which to start the next match.
+
+ +

Methods

+ +

The global RegExp object has no methods of its own. However, it does inherit some methods through the prototype chain.

+ +

RegExp prototype objects and instances

+ +

Properties

+ +
+

See also deprecated RegExp properties.

+ +

Note that several of the {{JSxRef("RegExp")}} properties have both long and short (Perl-like) names. Both names always refer to the same value. Perl is the programming language from which JavaScript modeled its regular expressions.

+ +
+
RegExp.prototype.constructor
+
Specifies the function that creates an object's prototype.
+
{{JSxRef("RegExp.prototype.flags")}}
+
A string that contains the flags of the RegExp object.
+
{{JSxRef("RegExp.prototype.dotAll")}}
+
Whether . matches newlines or not.
+
{{JSxRef("RegExp.prototype.global")}}
+
Whether to test the regular expression against all possible matches in a string, or only against the first.
+
{{JSxRef("RegExp.prototype.ignoreCase")}}
+
Whether to ignore case while attempting a match in a string.
+
{{JSxRef("RegExp.prototype.multiline")}}
+
Whether or not to search in strings across multiple lines.
+
{{JSxRef("RegExp.prototype.source")}}
+
The text of the pattern.
+
{{JSxRef("RegExp.prototype.sticky")}}
+
Whether or not the search is sticky.
+
{{JSxRef("RegExp.prototype.unicode")}}
+
Whether or not Unicode features are enabled.
+
+
+ +

Methods

+ +
+
+
{{JSxRef("RegExp.prototype.compile()")}}
+
(Re-)compiles a regular expression during execution of a script.
+
{{JSxRef("RegExp.prototype.exec()")}}
+
Executes a search for a match in its string parameter.
+
{{JSxRef("RegExp.prototype.test()")}}
+
Tests for a match in its string parameter.
+
{{JSxRef("RegExp.prototype.@@match()", "RegExp.prototype[@@match]()")}}
+
Performs match to given string and returns match result.
+
{{JSxRef("RegExp.prototype.@@matchAll()", "RegExp.prototype[@@matchAll]()")}}
+
Returns all matches of the regular expression against a string.
+
{{JSxRef("RegExp.prototype.@@replace()", "RegExp.prototype[@@replace]()")}}
+
Replaces matches in given string with new substring.
+
{{JSxRef("RegExp.prototype.@@search()", "RegExp.prototype[@@search]()")}}
+
Searches the match in given string and returns the index the pattern found in the string.
+
{{JSxRef("RegExp.prototype.@@split()", "RegExp.prototype[@@split]()")}}
+
Splits given string into an array by separating the string into substring.
+
{{JSxRef("RegExp.prototype.toSource()")}}
+
Returns an object literal representing the specified object; you can use this value to create a new object. Overrides the {{JSxRef("Object.prototype.toSource()")}} method.
+
{{JSxRef("RegExp.prototype.toString()")}}
+
Returns a string representing the specified object. Overrides the {{JSxRef("Object.prototype.toString()")}} method.
+
+
+ +

Examples

+ +

Using a regular expression to change data format

+ +

The following script uses the {{jsxref("String.prototype.replace()", "replace()")}} method of the {{jsxref("Global_Objects/String", "String")}} instance to match a name in the format first last and output it in the format last, first.

+ +

In the replacement text, the script uses $1 and $2 to indicate the results of the corresponding matching parentheses in the regular expression pattern.

+ +
let re = /(\w+)\s(\w+)/
+let str = 'John Smith'
+let newstr = str.replace(re, '$2, $1')
+console.log(newstr)
+
+ +

This displays "Smith, John".

+ +

Using regular expression to split lines with different line endings/ends of line/line breaks

+ +

The default line ending varies depending on the platform (Unix, Windows, etc.). The line splitting provided in this example works on all platforms.

+ +
let text = 'Some text\nAnd some more\r\nAnd yet\rThis is the end'
+let lines = text.split(/\r\n|\r|\n/)
+console.log(lines) // logs [ 'Some text', 'And some more', 'And yet', 'This is the end' ]
+
+ +

Note that the order of the patterns in the regular expression matters.

+ +

Using regular expression on multiple lines

+ +
let s = 'Please yes\nmake my day!'
+
+s.match(/yes.*day/);
+// Returns null
+
+s.match(/yes[^]*day/);
+// Returns ["yes\nmake my day"]
+
+ +

Using a regular expression with the sticky flag

+ +

The sticky flag indicates that the regular expression performs sticky matching in the target string by attempting to match starting at {{jsxref("RegExp.prototype.lastIndex")}}.

+ +
let str = '#foo#'
+let regex = /foo/y
+
+regex.lastIndex = 1
+regex.test(str)      // true
+regex.lastIndex = 5
+regex.test(str)      // false (lastIndex is taken into account with sticky flag)
+regex.lastIndex      // 0 (reset after match failure)
+ +

The difference between the sticky flag and the global flag

+ +

With the sticky flag y, the next match has to happen at the lastIndex position, while with the global flag g, the match can happen at the lastIndex position or later:

+ +
re = /\d/y;
+while (r = re.exec("123 456")) console.log(r, "AND re.lastIndex", re.lastIndex);
+
+// [ '1', index: 0, input: '123 456', groups: undefined ] AND re.lastIndex 1
+// [ '2', index: 1, input: '123 456', groups: undefined ] AND re.lastIndex 2
+// [ '3', index: 2, input: '123 456', groups: undefined ] AND re.lastIndex 3
+//   ... and no more match.
+ +

With the global flag g, all 6 digits would be matched, not just 3.

+ +

Regular expression and Unicode characters

+ +

As mentioned above, \w or \W only matches ASCII based characters; for example, a to z, A to Z, 0 to 9, and _.

+ +

To match characters from other languages such as Cyrillic or Hebrew, use \uhhhh, where hhhh is the character's Unicode value in hexadecimal.

+ +

This example demonstrates how one can separate out Unicode characters from a word.

+ +
let text = 'Образец text на русском языке'
+let regex = /[\u0400-\u04FF]+/g
+
+let match = regex.exec(text)
+console.log(match[0])        // logs 'Образец'
+console.log(regex.lastIndex) // logs '7'
+
+let match2 = regex.exec(text)
+console.log(match2[0])       // logs 'на' [did not log 'text']
+console.log(regex.lastIndex) // logs '15'
+
+// and so on
+
+ +

The Unicode property escapes feature introduces a solution, by allowing for a statement as simple as \p{scx=Cyrl}. One can also use an external resource for getting the complete Unicode block range for different scripts, such as Regexp-Unicode-block.

+ +

Extracting sub-domain name from URL

+ +
let url = 'http://xxx.domain.com'
+console.log(/[^.]+/.exec(url)[0].substr(7)) // logs 'xxx'
+
+ +

Specifications

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-regexp-regular-expression-objects', 'RegExp')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.builtins.RegExp")}}

+
+ +

Firefox-specific notes

+ +

Starting with Firefox 34, in the case of a capturing group with quantifiers preventing its exercise, the matched text for a capturing group is now undefined instead of an empty string:

+ +
// Firefox 33 or older
+'x'.replace(/x(.)?/g, function(m, group) {
+  console.log("'group:" + group + "'");
+});
+// 'group:'
+
+// Firefox 34 or newer
+'x'.replace(/x(.)?/g, function(m, group) {
+  console.log("'group:" + group + "'");
+});
+// 'group:undefined'
+
+ +

Note that due to web compatibility, RegExp.$N will still return an empty string instead of undefined (bug 1053944).

+ +

See also

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/set/add/index.html b/files/zh-tw/web/javascript/reference/global_objects/set/add/index.html new file mode 100644 index 0000000000..b0a85a0a06 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/set/add/index.html @@ -0,0 +1,83 @@ +--- +title: Set.prototype.add() +slug: Web/JavaScript/Reference/Global_Objects/Set/add +tags: + - ECMAScript 2015 + - JavaScript + - 原型 + - 參考 + - 方法 + - 集合 +translation_of: Web/JavaScript/Reference/Global_Objects/Set/add +--- +
{{JSRef}}
+ +

add() 會在一個 Set 物件的尾端加上一個指定 value 的新元素。

+ +
{{EmbedInteractiveExample("pages/js/set-prototype-add.html")}}
+ + + +

語法

+ +
mySet.add(value);
+ +

參數

+ +
+
value
+
要被加到 Set 物件中的值。
+
+ +

回傳值

+ +

Set 物件本身。

+ +

範例

+ +

使用 add 方法

+ +
var mySet = new Set();
+
+mySet.add(1);
+mySet.add(5).add('some text'); // chainable
+
+console.log(mySet);
+// Set [1, 5, "some text"]
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
規範狀態
{{SpecName('ES2015', '#sec-set.prototype.add', 'Set.prototype.add')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-set.prototype.add', 'Set.prototype.add')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.Set.add")}}

+ +

另見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/set/clear/index.html b/files/zh-tw/web/javascript/reference/global_objects/set/clear/index.html new file mode 100644 index 0000000000..2eb8875c34 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/set/clear/index.html @@ -0,0 +1,79 @@ +--- +title: Set.prototype.clear() +slug: Web/JavaScript/Reference/Global_Objects/Set/clear +tags: + - ECMAScript 2015 + - JavaScript + - 原型 + - 參考 + - 方法 + - 集合 +translation_of: Web/JavaScript/Reference/Global_Objects/Set/clear +--- +
{{JSRef}}
+ +

clear() 方法會從一個 Set 物件中移除其所有元素。

+ +
{{EmbedInteractiveExample("pages/js/set-prototype-clear.html")}}
+ + + +

語法

+ +
mySet.clear();
+ +

回傳值

+ +

{{jsxref("undefined")}}.

+ +

範例

+ +

使用 clear 方法

+ +
var mySet = new Set();
+mySet.add(1);
+mySet.add('foo');
+
+mySet.size;       // 2
+mySet.has('foo'); // true
+
+mySet.clear();
+
+mySet.size;       // 0
+mySet.has('bar')  // false
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
規範狀態
{{SpecName('ES2015', '#sec-set.prototype.clear', 'Set.prototype.clear')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-set.prototype.clear', 'Set.prototype.clear')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.Set.clear")}}

+ +

另見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/set/delete/index.html b/files/zh-tw/web/javascript/reference/global_objects/set/delete/index.html new file mode 100644 index 0000000000..d465f45bef --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/set/delete/index.html @@ -0,0 +1,98 @@ +--- +title: Set.prototype.delete() +slug: Web/JavaScript/Reference/Global_Objects/Set/delete +tags: + - ECMAScript 2015 + - JavaScript + - 原型 + - 參考 + - 方法 + - 集合 +translation_of: Web/JavaScript/Reference/Global_Objects/Set/delete +--- +
{{JSRef}}
+ +

delete() 方法會一個 Set 物件中移除指定元素。

+ +
{{EmbedInteractiveExample("pages/js/set-prototype-delete.html")}}
+ + + +

語法

+ +
mySet.delete(value);
+ +

參數'

+ +
+
value
+
要從 Set 物件中移除的值。
+
+ +

回傳值

+ +

true 如果成功從 Set 物件中移除;反之 false

+ +

範例

+ +

使用 delete 方法

+ +
var mySet = new Set();
+mySet.add('foo');
+
+mySet.delete('bar'); // Returns false. No "bar" element found to be deleted.
+mySet.delete('foo'); // Returns true.  Successfully removed.
+
+mySet.has('foo');    // Returns false. The "foo" element is no longer present.
+
+ +

下方展示了如何從一個 Set 中移除物件。

+ +
var setObj = new Set(); // Create a New Set.
+
+setObj.add({x: 10, y: 20}); // Add object in the set.
+
+setObj.add({x: 20, y: 30}); // Add object in the set.
+
+// Delete any point with `x > 10`.
+setObj.forEach(function(point){
+  if(point.x > 10){
+    setObj.delete(point)
+  }
+})
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
規範狀態
{{SpecName('ES2015', '#sec-set.prototype.delete', 'Set.prototype.delete')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-set.prototype.delete', 'Set.prototype.delete')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.Set.delete")}}

+ +

另見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/set/entries/index.html b/files/zh-tw/web/javascript/reference/global_objects/set/entries/index.html new file mode 100644 index 0000000000..6bf609afb2 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/set/entries/index.html @@ -0,0 +1,78 @@ +--- +title: Set.prototype.entries() +slug: Web/JavaScript/Reference/Global_Objects/Set/entries +tags: + - ECMAScript 2015 + - JavaScript + - 原型 + - 方法 + - 迭代器 + - 集合 +translation_of: Web/JavaScript/Reference/Global_Objects/Set/entries +--- +
{{JSRef}}
+ +
entries() 方法回傳一個 Iterator 物件,其包含著一個由插入順序排序,Set 物件中每個元素的 [value, value] 陣列。儘管對 Set 物件來說沒有像 Map 一樣的 key 概念,為了確保這個 API 運作的與 Map 相似,每個 entry 都有同樣的值同時作為其 keyvalue ,因此回傳的是一個[value, value] 的陣列。
+ +
{{EmbedInteractiveExample("pages/js/set-prototype-entries.html")}}
+ + + +

語法

+ +
mySet.entries()
+ +

回傳值

+ +

一個新的 Iterator 物件,包含著一個由插入順序排序,Set 物件中每個元素的 [value, value] 陣列。

+ +

範例

+ +

使用 entries()

+ +
var mySet = new Set();
+mySet.add('foobar');
+mySet.add(1);
+mySet.add('baz');
+
+var setIter = mySet.entries();
+
+console.log(setIter.next().value); // ["foobar", "foobar"]
+console.log(setIter.next().value); // [1, 1]
+console.log(setIter.next().value); // ["baz", "baz"]
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
規範狀態
{{SpecName('ES2015', '#sec-set.prototype.entries', 'Set.prototype.entries')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-set.prototype.entries', 'Set.prototype.entries')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.Set.entries")}}

+ +

另見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/set/has/index.html b/files/zh-tw/web/javascript/reference/global_objects/set/has/index.html new file mode 100644 index 0000000000..c77d2ea99b --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/set/has/index.html @@ -0,0 +1,92 @@ +--- +title: Set.prototype.has() +slug: Web/JavaScript/Reference/Global_Objects/Set/has +tags: + - ECMAScript 2015 + - JavaScript + - 原型 + - 方法 + - 集合 +translation_of: Web/JavaScript/Reference/Global_Objects/Set/has +--- +
{{JSRef}}
+ +

has() 方法對一個指定值元素在 Set 物件中的存在與否回傳一個布林值。

+ +
{{EmbedInteractiveExample("pages/js/set-prototype-has.html")}}
+ + + +

語法

+ +
mySet.has(value);
+ +

參數

+ +
+
value
+
要測試是否存在在 Set 中的值。
+
+ +

回傳值

+ +

回傳 true 如果給定值存在在 Set 物件中;反之回傳 false

+ +
+

Note: 技術上來說,has() 使用了 sameValueZero 算法來判斷給定元素的存在與否。

+
+ +

範例

+ +

使用 has 方法

+ +
var mySet = new Set();
+mySet.add('foo');
+
+mySet.has('foo');  // returns true
+mySet.has('bar');  // returns false
+
+var set1 = new Set();
+var obj1 = {'key1': 1};
+set1.add(obj1);
+
+set1.has(obj1);        // returns true
+set1.has({'key1': 1}); // returns false because they are different object references
+set1.add({'key1': 1}); // now set1 contains 2 entries
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
規範狀態
{{SpecName('ES2015', '#sec-set.prototype.has', 'Set.prototype.has')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-set.prototype.has', 'Set.prototype.has')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.Set.has")}}

+ +

另見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/set/index.html b/files/zh-tw/web/javascript/reference/global_objects/set/index.html new file mode 100644 index 0000000000..2b3f80fdd1 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/set/index.html @@ -0,0 +1,243 @@ +--- +title: Set +slug: Web/JavaScript/Reference/Global_Objects/Set +tags: + - ECMAScript 2015 + - Global Objects + - JavaScript + - Object + - set +translation_of: Web/JavaScript/Reference/Global_Objects/Set +--- +
{{JSRef}}
+ +

Set 物件可讓你儲存任何類型的唯一值(unique),不論是{{Glossary("Primitive", "基本型別(primitive)值")}}或物件參考(references)。

+ +
{{EmbedInteractiveExample("pages/js/set-prototype-constructor.html")}}
+ + + +

語法

+ +
new Set([iterable]);
+ +

參數

+ +
+
iterable
+
若一個可迭代物件被傳入,其所有的元素將會被加入至新的 Set。若你沒有指定此參數,或參數值為 null,則新的 Set 會是空的。
+
+ +

回傳值

+ +

一個新的 Set 物件。

+ +

描述

+ +

Set 對象是數值的收集器。您可以按插入順序迭代收集器中的元素。在 Set 裡的元素只會出現一次 意即在Set裡的元素都是獨一無二

+ +

值的相等性

+ +

因為在 Set 裡每個值都是獨立的,所以都會檢查值的相等性。在早期的ECMAScript規範版本中,此處算法跟基於===操作符中使用的算法並不相同。具體來說,在 Set裡+0(在嚴格模式是和-0相等)和-0是不同的值。然而在 ECMAScript 2015規範中這點已被更改。請參閱 瀏覽器兼容性 中的"Value equality for -0 and 0"。

+ +

另外,NaN和undefined都可以被放置在Set 中, NaN之間被視為相同的值(儘管 NaN !== NaN)。

+ +
+
Set.length
+
The value of the length property is 0.
+
{{jsxref("Set.@@species", "get Set[@@species]")}}
+
The constructor function that is used to create derived objects.
+
{{jsxref("Set.prototype")}}
+
Represents the prototype for the Set constructor. Allows the addition of properties to all Set objects.
+
+ +

Set 物件實體

+ +

All Set instances inherit from {{jsxref("Set.prototype")}}.

+ +

屬性

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Set/prototype','Properties')}}

+ +

方法

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/Set/prototype','Methods')}}

+ +

範例

+ +

使用 Set 物件

+ +
var mySet = new Set();
+
+mySet.add(1); // Set [ 1 ]
+mySet.add(5); // Set [ 1, 5 ]
+mySet.add(5); // Set [ 1, 5 ]
+mySet.add('some text'); // Set [ 1, 5, 'some text' ]
+var o = {a: 1, b: 2};
+mySet.add(o);
+
+mySet.add({a: 1, b: 2}); // o is referencing a different object so this is okay
+
+mySet.has(1); // true
+mySet.has(3); // false, 3 has not been added to the set
+mySet.has(5);              // true
+mySet.has(Math.sqrt(25));  // true
+mySet.has('Some Text'.toLowerCase()); // true
+mySet.has(o); // true
+
+mySet.size; // 5
+
+mySet.delete(5); // removes 5 from the set
+mySet.has(5);    // false, 5 has been removed
+
+mySet.size; // 4, we just removed one value
+console.log(mySet);// Set [ 1, "some text", Object {a: 1, b: 2}, Object {a: 1, b: 2} ]
+ +

迭代 Sets

+ +
// iterate over items in set
+// logs the items in the order: 1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}
+for (let item of mySet) console.log(item);
+
+// logs the items in the order: 1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}
+for (let item of mySet.keys()) console.log(item);
+
+// logs the items in the order: 1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}
+for (let item of mySet.values()) console.log(item);
+
+// logs the items in the order: 1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}
+//(key and value are the same here)
+for (let [key, value] of mySet.entries()) console.log(key);
+
+// convert Set object to an Array object, with Array.from
+var myArr = Array.from(mySet); // [1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2}]
+
+// the following will also work if run in an HTML document
+mySet.add(document.body);
+mySet.has(document.querySelector('body')); // true
+
+// converting between Set and Array
+mySet2 = new Set([1, 2, 3, 4]);
+mySet2.size; // 4
+[...mySet2]; // [1, 2, 3, 4]
+
+// intersect can be simulated via
+var intersection = new Set([...set1].filter(x => set2.has(x)));
+
+// difference can be simulated via
+var difference = new Set([...set1].filter(x => !set2.has(x)));
+
+// Iterate set entries with forEach
+mySet.forEach(function(value) {
+  console.log(value);
+});
+
+// 1
+// 2
+// 3
+// 4
+ +

實作基本的 set 操作

+ +
Set.prototype.isSuperset = function(subset) {
+    for (var elem of subset) {
+        if (!this.has(elem)) {
+            return false;
+        }
+    }
+    return true;
+}
+
+Set.prototype.union = function(setB) {
+    var union = new Set(this);
+    for (var elem of setB) {
+        union.add(elem);
+    }
+    return union;
+}
+
+Set.prototype.intersection = function(setB) {
+    var intersection = new Set();
+    for (var elem of setB) {
+        if (this.has(elem)) {
+            intersection.add(elem);
+        }
+    }
+    return intersection;
+}
+
+Set.prototype.difference = function(setB) {
+    var difference = new Set(this);
+    for (var elem of setB) {
+        difference.delete(elem);
+    }
+    return difference;
+}
+
+//Examples
+var setA = new Set([1, 2, 3, 4]),
+    setB = new Set([2, 3]),
+    setC = new Set([3, 4, 5, 6]);
+
+setA.isSuperset(setB); // => true
+setA.union(setC); // => Set [1, 2, 3, 4, 5, 6]
+setA.intersection(setC); // => Set [3, 4]
+setA.difference(setC); // => Set [1, 2]
+
+
+ +

與 Array 物件關聯

+ +
var myArray = ['value1', 'value2', 'value3'];
+
+// Use the regular Set constructor to transform an Array into a Set
+var mySet = new Set(myArray);
+
+mySet.has('value1'); // returns true
+
+// Use the spread operator to transform a set into an Array.
+console.log([...mySet]); // Will show you exactly the same Array as myArray
+ +

與 Strings 關聯

+ +
var text = 'India';
+
+var mySet = new Set(text);  // Set ['I', 'n', 'd', 'i', 'a']
+mySet.size;  // 5
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-set-objects', 'Set')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-set-objects', 'Set')}}{{Spec2('ESDraft')}}
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.Set")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/set/values/index.html b/files/zh-tw/web/javascript/reference/global_objects/set/values/index.html new file mode 100644 index 0000000000..bb136ba806 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/set/values/index.html @@ -0,0 +1,79 @@ +--- +title: Set.prototype.values() +slug: Web/JavaScript/Reference/Global_Objects/Set/values +tags: + - ECMAScript 2015 + - JavaScript + - 原型 + - 方法 + - 迭代器 + - 集合 +translation_of: Web/JavaScript/Reference/Global_Objects/Set/values +--- +
{{JSRef}}
+ +

values() 方法回傳一個 Iterator 物件,包含著 Set 物件中所有元素,由插入順序排序。

+ +

keys() 是這個方法的替身 (為了與 {{jsxref("Map")}} 物件保持相似性);他運行的完全一模一樣,回傳 Set 中元素的 values

+ +
{{EmbedInteractiveExample("pages/js/set-prototype-values.html")}}
+ + + +

語法

+ +
mySet.values();
+
+ +

回傳值

+ +

一個 Iterator 物件,包含著 Set 物件中所有元素,由插入順序排序。

+ +

範例

+ +

使用 values()

+ +
var mySet = new Set();
+mySet.add('foo');
+mySet.add('bar');
+mySet.add('baz');
+
+var setIter = mySet.values();
+
+console.log(setIter.next().value); // "foo"
+console.log(setIter.next().value); // "bar"
+console.log(setIter.next().value); // "baz"
+ +

規範

+ + + + + + + + + + + + + + + + + + + +
規範狀態
{{SpecName('ES2015', '#sec-set.prototype.values', 'Set.prototype.values')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-set.prototype.values', 'Set.prototype.values')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.Set.values")}}

+ +

另見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/string/index.html b/files/zh-tw/web/javascript/reference/global_objects/string/index.html new file mode 100644 index 0000000000..ad4474693a --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/string/index.html @@ -0,0 +1,328 @@ +--- +title: 字串 +slug: Web/JavaScript/Reference/Global_Objects/String +tags: + - ECMAScript 2015 + - JavaScript + - Reference + - String +translation_of: Web/JavaScript/Reference/Global_Objects/String +--- +

{{JSRef("Global_Objects", "String")}}

+ +

String 全域物件為字串的構造函數,或是一個字符序列。

+ +

語法

+ +

字串文字採用下列形式:

+ +
'string text' "string text" "中文 español deutsch English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어 தமிழ் עברית"
+ +

字串也可以被全域的 String 物件建立:

+ +
String(thing)
+ +

參數

+ +
+
thing
+
任何要轉換成字串的物件。
+
+ +

樣板字面值

+ +

自 ECMAScript 2015,字串文字也可以是樣板字面值(Template literals)

+ +
`hello world` `hello! world!` `hello ${who}` escape `<a>${who}</a>`
+ +

跳脫符號

+ +

除了常規的、可印出來的字元,特殊字元也可以被跳脫符號來表示編碼。

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
代碼輸出
\0空字元
\'單引號
\"雙引號
\\反斜線
\n斷行
\r回車
\v垂直制表
\t制表
\b退格
\f饋頁
\uXXXXunicode 代碼
\u{X} ... \u{XXXXXX}unicode 代碼 {{experimental_inline}}
\xXXLatin-1 字元
+ +
+
+ +
+

和其他語言不同,JavaScript 將單引號字串和雙引號字串是做相同;因此,上述的序列可以在單引號或雙引號中作用。

+
+ +
+
+ +

長字面值字串

+ +

有些時候,你的程式碼會包含非常長的字串。 為了不讓長字串無止盡地往下長,抑或是在你心血來潮的時候,你可能希望將這樣長的字串能夠斷成多行卻不影響到實際的內容。

+ +

你可以用 + 運算子附加多個字串在一起,像是這樣:

+ +
let longString = "This is a very long string which needs " +
+                 "to wrap across multiple lines because " +
+                 "otherwise my code is unreadable.";
+ +

或者,你可以在每一行尾端用反斜線字元("\")表示字串會繼續被顯示在下一列。 你必須要確定在反斜線後面沒有任何空白或其他字元,甚至是縮排;否則這個方法將失效。 這個形式看起來像這樣:

+ +
let longString = "This is a very long string which needs \
+to wrap across multiple lines because \
+otherwise my code is unreadable.";
+ +

這兩個方法都會建立相同的字串內容。

+ +

說明

+ +

字串對於能保留以文字形式表達的資料這件事來說,是有用的。在字串上,一些最常被使用的運算即確認字串長度 {{jsxref("String.length", "length")}} ,用 + 或 += 字串運算元 建造或者串接字串,用 {{jsxref("String.indexOf", "indexOf")}} 方法檢查?子字串是否存在或子字串的位置,或者是用 {{jsxref("String.substring", "substring")}} 方法將子字串抽取出來。

+ +

存取字元

+ +

有兩個方法可以存取字串中個別的字元。第一個是用 {{jsxref("String.charAt", "charAt")}} 方法:

+ +
return 'cat'.charAt(1); // 回傳 "a"
+
+ +

另一個(在ECMAScript 5中被提到)方法是將字串當作一個類似陣列的物件,直接存取字串中對應的數值索引。

+ +
return 'cat'[1]; // 回傳 "a"
+
+ +

對於存取字元使用的括號表達式,沒辦法去刪除或指派一個值給這些屬性。 這些屬性既非可寫的,也非可設定的。(參見 {{jsxref("Object.defineProperty")}})

+ +

比較字串

+ +

C 語言的開發者有 strcmp() 函式可以用來比較字串。 在 JavaScript 中,你只能用小於和大於運算子

+ +
var a = "a";
+var b = "b";
+if (a < b) // true
+  print(a + " 小於 " + b);
+else if (a > b)
+  print(a + " 大於 " + b);
+else
+  print(a + " 和 " + b + " 相等");
+
+ +

這樣類似的結果,也能使用繼承 String 實體的 {{jsxref("String.localeCompare", "localeCompare")}} 方法來實現。

+ +

分辨 string 原始型別和 String 物件

+ +

請注意,JavaScript 會區別 String 物件和原始字串({{jsxref("Global_Objects/Boolean", "Boolean")}} 和 {{jsxref("Global_Objects/Number", "Numbers")}} 也是如此)。

+ +

String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the new keyword) are primitive strings. JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.

+ +
var s_prim = "foo";
+var s_obj = new String(s_prim);
+
+console.log(typeof s_prim); // 印出 "string"
+console.log(typeof s_obj);  // 印出 "object"
+
+ +

字串原始型別和 String 物件也會在使用 {{jsxref("Global_Objects/eval", "eval")}} 時給出不同的結果。 原始型別傳進 eval 會被視為原始代碼;String 物件則會回傳,且被視作是其他物件。舉個例子:

+ +
s1 = "2 + 2";               // 建立一個字串原始型別
+s2 = new String("2 + 2");   // 建立一個字串物件
+console.log(eval(s1));      // 回傳數字 4
+console.log(eval(s2));      // 回傳字串 "2 + 2"
+
+ +

因為一些原因,程式碼也許在遇到 String 物件時,但需要的卻是字串原始型別;儘管如此,通常作者們不需要擔心它的差異。

+ +

一個 String 物件總能夠使用 {{jsxref("String.valueOf", "valueOf")}} 方法被轉換成自身的原始副本。

+ +
console.log(eval(s2.valueOf())); // 回傳數字 4
+
+ +
注意: 對於在 JavaScript 中其他可用的字串方法,請參閱這篇文章StringView – a C-like representation of strings based on typed arrays
+ +

屬性

+ +
+
{{jsxref("String.prototype")}}
+
能讓字串物件增加屬性。
+
+ +
{{jsOverrides("Function", "Properties", "prototype")}}
+ +

方法

+ +
+
{{jsxref("String.fromCharCode()")}}
+
利用 Unicode 值的序列建立並回傳一個字串。
+
{{jsxref("String.fromCodePoint()")}} {{experimental_inline}}
+
利用編碼位置的序列建立並回傳一個字串。
+
+ +
{{jsOverrides("Function", "Methods", "fromCharCode", "fromCodePoint")}}
+ +

String 通用方法

+ +
+

字串通用方法是非標準化的、被棄用的,也有近期將被刪除的。

+
+ +

The String instance methods are also available in Firefox as of JavaScript 1.6 (though not part of the ECMAScript standard) on the String object for applying String methods to any object:

+ +
var num = 15;
+alert(String.replace(num, /5/, '2'));
+
+ +

Generics are also available on {{jsxref("Global_Objects/Array", "Array")}} methods.

+ +

The following is a shim to provide support to non-supporting browsers:

+ +
/*globals define*/
+// Assumes all supplied String instance methods already present
+// (one may use shims for these if not available)
+(function () {
+    'use strict';
+
+    var i,
+        // We could also build the array of methods with the following, but the
+        //   getOwnPropertyNames() method is non-shimable:
+        // Object.getOwnPropertyNames(String).filter(function (methodName)
+        //  {return typeof String[methodName] === 'function'});
+        methods = [
+            'quote', 'substring', 'toLowerCase', 'toUpperCase', 'charAt',
+            'charCodeAt', 'indexOf', 'lastIndexOf', 'startsWith', 'endsWith',
+            'trim', 'trimLeft', 'trimRight', 'toLocaleLowerCase',
+            'toLocaleUpperCase', 'localeCompare', 'match', 'search',
+            'replace', 'split', 'substr', 'concat', 'slice'
+        ],
+        methodCount = methods.length,
+        assignStringGeneric = function (methodName) {
+            var method = String.prototype[methodName];
+            String[methodName] = function (arg1) {
+                return method.apply(arg1, Array.prototype.slice.call(arguments, 1));
+            };
+        };
+
+    for (i = 0; i < methodCount; i++) {
+        assignStringGeneric(methods[i]);
+    }
+}());
+ +

String instances

+ +

Properties

+ +

{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Properties')}}

+ +

{{page('en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods')}}

+ +

Examples

+ +

String conversion

+ +

It's possible to use String as a "safer" {{jsxref("String.toString", "toString")}} alternative, as although it still normally calls the underlying toString, it also works for null and undefined. For example:

+ +
var outputStrings = [];
+for (let i = 0, n = inputValues.length; i < n; ++i) {
+  outputStrings.push(String(inputValues[i]));
+}
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.5', 'String')}}{{Spec2('ES5.1')}} 
{{SpecName('ES2015', '#sec-string-objects', 'String')}}{{Spec2('ES2015')}} 
{{SpecName('ESDraft', '#sec-string-objects', 'String')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.String.String")}}

+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/string/match/index.html b/files/zh-tw/web/javascript/reference/global_objects/string/match/index.html new file mode 100644 index 0000000000..664b28462f --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/string/match/index.html @@ -0,0 +1,151 @@ +--- +title: String.prototype.match() +slug: Web/JavaScript/Reference/Global_Objects/String/match +translation_of: Web/JavaScript/Reference/Global_Objects/String/match +--- +
{{JSRef}}
+ +

The match() method retrieves the matches when matching a string against a regular expression.

+ +

Syntax

+ +
str.match(regexp)
+ +

Parameters

+ +
+
regexp
+
一個正規表達式的物件。 若傳入一個非正規表達式的物件obj,則會視為傳入 new RegExp(obj)。若只呼叫match()而沒有傳入任何參數,則會回傳內含一個空字串的陣列,即[""]
+
+ +

Return value

+ +

If the string matches the expression, it will return an {{jsxref("Array")}} containing the entire matched string as the first element, followed by any results captured in parentheses. If there were no matches, {{jsxref("null")}} is returned.

+ +

Description

+ +

If the regular expression does not include the g flag, str.match() will return the same result as {{jsxref("RegExp.prototype.exec()", "RegExp.exec()")}}. The returned {{jsxref("Array")}} has an extra input property, which contains the original string that was parsed. In addition, it has an index property, which represents the zero-based index of the match in the string.

+ +

If the regular expression includes the g flag, the method returns an {{jsxref("Array")}} containing all matched substrings rather than match objects. Captured groups are not returned. If there were no matches, the method returns {{jsxref("null")}}.

+ +

See also: RegExp methods

+ + + +

Examples

+ +

Using match()

+ +

In the following example, match() is used to find 'Chapter' followed by 1 or more numeric characters followed by a decimal point and numeric character 0 or more times. The regular expression includes the i flag so that upper/lower case differences will be ignored.

+ +
var str = 'For more information, see Chapter 3.4.5.1';
+var re = /see (chapter \d+(\.\d)*)/i;
+var found = str.match(re);
+
+console.log(found);
+
+// logs [ 'see Chapter 3.4.5.1',
+//        'Chapter 3.4.5.1',
+//        '.1',
+//        index: 22,
+//        input: 'For more information, see Chapter 3.4.5.1' ]
+
+// 'see Chapter 3.4.5.1' is the whole match.
+// 'Chapter 3.4.5.1' was captured by '(chapter \d+(\.\d)*)'.
+// '.1' was the last value captured by '(\.\d)'.
+// The 'index' property (22) is the zero-based index of the whole match.
+// The 'input' property is the original string that was parsed.
+ +

Using global and ignore case flags with match()

+ +

The following example demonstrates the use of the global and ignore case flags with match(). All letters A through E and a through e are returned, each its own element in the array.

+ +
var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
+var regexp = /[A-E]/gi;
+var matches_array = str.match(regexp);
+
+console.log(matches_array);
+// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']
+
+ +

Using match() with no parameter

+ +
var str = "Nothing will come of nothing.";
+
+str.match();   // returns [""]
+ +

A non-RegExp object as the parameter

+ +

When the parameter is a string or a number, it is implicitly converted to a {{jsxref("RegExp")}} by using new RegExp(obj). If it is a positive number with a positive sign,the RegExp() method will ignore the positive sign. 

+ +
var str1 = "NaN means not a number. Infinity contains -Infinity and +Infinity in JavaScript.",
+    str2 = "My grandfather is 65 years old and My grandmother is 63 years old.",
+    str3 = "The contract was declared null and void.";
+str1.match("number");   // "number" is a string. returns ["number"]
+str1.match(NaN);        // the type of NaN is the number. returns ["NaN"]
+str1.match(Infinity);   // the type of Infinity is the number. returns ["Infinity"]
+str1.match(+Infinity);  // returns ["Infinity"]
+str1.match(-Infinity);  // returns ["-Infinity"]
+str2.match(65);         // returns ["65"]
+str2.match(+65);        // A number with a positive sign. returns ["65"]
+str3.match(null);       // returns ["null"]
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.4.10', 'String.prototype.match')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.match', 'String.prototype.match')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.match', 'String.prototype.match')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.String.match")}}

+ +

Firefox-specific notes

+ + + +

See also

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/string/padstart/index.html b/files/zh-tw/web/javascript/reference/global_objects/string/padstart/index.html new file mode 100644 index 0000000000..8a08d5924f --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/string/padstart/index.html @@ -0,0 +1,96 @@ +--- +title: String.prototype.padStart() +slug: Web/JavaScript/Reference/Global_Objects/String/padStart +translation_of: Web/JavaScript/Reference/Global_Objects/String/padStart +--- +
{{JSRef}}{{SeeCompatTable}}
+ +

padStart() 會將用給定用於填充的字串,以重複的方式,插入到目標字串的起頭(左側),直到目標字串到達指定長度。

+ +

Syntax

+ +
str.padStart(targetLength [, padString])
+ +

Parameters

+ +
+
targetLength
+
目標字串被填充後的長度。如果此參數小於原字串的長度,那將直接返回原字串。
+
padString {{optional_inline}}
+
用來填充的字串。如果填充字串太長,則由左側開始,擷取所需要的長度。此參數預設值是空白 " " (U+0020).
+
+ +

Return value

+ +

目標字串被填充到指定長度後,所得的新字串。

+ +

Examples

+ +
'abc'.padStart(10);         // "       abc"
+'abc'.padStart(10, "foo");  // "foofoofabc"
+'abc'.padStart(6,"123465"); // "123abc"
+
+ +

Specifications

+ +

這個方法還沒有被納入 ECMAScript 標準。現在還只是個提案

+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome(57)}} 15{{CompatGeckoDesktop(51)}}{{CompatNo}}{{CompatOpera(44)}}{{CompatSafari(10)}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatUnknown}}{{CompatChrome(57)}}{{CompatGeckoMobile(51)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatSafari(10)}}
+
+ +

See also

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/string/prototype/index.html b/files/zh-tw/web/javascript/reference/global_objects/string/prototype/index.html new file mode 100644 index 0000000000..41c7333dc6 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/string/prototype/index.html @@ -0,0 +1,176 @@ +--- +title: String.prototype +slug: Web/JavaScript/Reference/Global_Objects/String/prototype +translation_of: Web/JavaScript/Reference/Global_Objects/String +--- +
{{JSRef}}
+ +

The String.prototype property represents the {{jsxref("String")}} prototype object.

+ +
{{js_property_attributes(0, 0, 0)}}
+ +

Description

+ +

All {{jsxref("String")}} instances inherit from String.prototype. Changes to the String prototype object are propagated to all {{jsxref("String")}} instances.

+ +

Properties

+ +
+
String.prototype.constructor
+
Specifies the function that creates an object's prototype.
+
{{jsxref("String.prototype.length")}}
+
Reflects the length of the string.
+
N
+
Used to access the character in the Nth position where N is a positive integer between 0 and one less than the value of {{jsxref("String.length", "length")}}. These properties are read-only.
+
+ +

Methods

+ +

Methods unrelated to HTML

+ +
+
{{jsxref("String.prototype.charAt()")}}
+
Returns the character (exactly one UTF-16 code unit) at the specified index.
+
{{jsxref("String.prototype.charCodeAt()")}}
+
Returns a number that is the UTF-16 code unit value at the given index.
+
{{jsxref("String.prototype.codePointAt()")}}
+
Returns a nonnegative integer Number that is the code point value of the UTF-16 encoded code point starting at the specified index.
+
{{jsxref("String.prototype.concat()")}}
+
Combines the text of two strings and returns a new string.
+
{{jsxref("String.prototype.includes()")}}
+
Determines whether one string may be found within another string.
+
{{jsxref("String.prototype.endsWith()")}}
+
Determines whether a string ends with the characters of another string.
+
{{jsxref("String.prototype.indexOf()")}}
+
Returns the index within the calling {{jsxref("String")}} object of the first occurrence of the specified value, or -1 if not found.
+
{{jsxref("String.prototype.lastIndexOf()")}}
+
Returns the index within the calling {{jsxref("String")}} object of the last occurrence of the specified value, or -1 if not found.
+
{{jsxref("String.prototype.localeCompare()")}}
+
Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
+
{{jsxref("String.prototype.match()")}}
+
Used to match a regular expression against a string.
+
{{jsxref("String.prototype.normalize()")}}
+
Returns the Unicode Normalization Form of the calling string value.
+
{{jsxref("String.prototype.padEnd()")}}
+
Pads the current string from the end with a given string to create a new string from a given length.
+
{{jsxref("String.prototype.padStart()")}}
+
Pads the current string from the start with a given string to create a new string from a given length.
+
{{jsxref("String.prototype.quote()")}} {{obsolete_inline}}
+
Wraps the string in double quotes (""").
+
{{jsxref("String.prototype.repeat()")}}
+
Returns a string consisting of the elements of the object repeated the given times.
+
{{jsxref("String.prototype.replace()")}}
+
Used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.
+
{{jsxref("String.prototype.search()")}}
+
Executes the search for a match between a regular expression and a specified string.
+
{{jsxref("String.prototype.slice()")}}
+
Extracts a section of a string and returns a new string.
+
{{jsxref("String.prototype.split()")}}
+
Splits a {{jsxref("Global_Objects/String", "String")}} object into an array of strings by separating the string into substrings.
+
{{jsxref("String.prototype.startsWith()")}}
+
Determines whether a string begins with the characters of another string.
+
{{jsxref("String.prototype.substr()")}}
+
Returns the characters in a string beginning at the specified location through the specified number of characters.
+
{{jsxref("String.prototype.substring()")}}
+
Returns the characters in a string between two indexes into the string.
+
{{jsxref("String.prototype.toLocaleLowerCase()")}}
+
The characters within a string are converted to lower case while respecting the current locale. For most languages, this will return the same as {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}}.
+
{{jsxref("String.prototype.toLocaleUpperCase()")}}
+
The characters within a string are converted to upper case while respecting the current locale. For most languages, this will return the same as {{jsxref("String.prototype.toUpperCase()", "toUpperCase()")}}.
+
{{jsxref("String.prototype.toLowerCase()")}}
+
Returns the calling string value converted to lower case.
+
{{jsxref("String.prototype.toSource()")}} {{non-standard_inline}}
+
Returns an object literal representing the specified object; you can use this value to create a new object. Overrides the {{jsxref("Object.prototype.toSource()")}} method.
+
{{jsxref("String.prototype.toString()")}}
+
Returns a string representing the specified object. Overrides the {{jsxref("Object.prototype.toString()")}} method.
+
{{jsxref("String.prototype.toUpperCase()")}}
+
Returns the calling string value converted to uppercase.
+
{{jsxref("String.prototype.trim()")}}
+
Trims whitespace from the beginning and end of the string. Part of the ECMAScript 5 standard.
+
{{jsxref("String.prototype.trimLeft()")}} {{non-standard_inline}}
+
Trims whitespace from the left side of the string.
+
{{jsxref("String.prototype.trimRight()")}} {{non-standard_inline}}
+
Trims whitespace from the right side of the string.
+
{{jsxref("String.prototype.valueOf()")}}
+
Returns the primitive value of the specified object. Overrides the {{jsxref("Object.prototype.valueOf()")}} method.
+
{{jsxref("String.prototype.@@iterator()", "String.prototype[@@iterator]()")}}
+
Returns a new Iterator object that iterates over the code points of a String value, returning each code point as a String value.
+
+ +

HTML wrapper methods

+ +

These methods are of limited use, as they provide only a subset of the available HTML tags and attributes.

+ +
+
{{jsxref("String.prototype.anchor()")}}
+
{{htmlattrxref("name", "a", "<a name=\"name\">")}} (hypertext target)
+
{{jsxref("String.prototype.big()")}} {{deprecated_inline}}
+
{{HTMLElement("big")}}
+
{{jsxref("String.prototype.blink()")}} {{deprecated_inline}}
+
{{HTMLElement("blink")}}
+
{{jsxref("String.prototype.bold()")}} {{deprecated_inline}}
+
{{HTMLElement("b")}}
+
{{jsxref("String.prototype.fixed()")}} {{deprecated_inline}}
+
{{HTMLElement("tt")}}
+
{{jsxref("String.prototype.fontcolor()")}} {{deprecated_inline}}
+
{{htmlattrxref("color", "font", "<font color=\"color\">")}}
+
{{jsxref("String.prototype.fontsize()")}} {{deprecated_inline}}
+
{{htmlattrxref("size", "font", "<font size=\"size\">")}}
+
{{jsxref("String.prototype.italics()")}} {{deprecated_inline}}
+
{{HTMLElement("i")}}
+
{{jsxref("String.prototype.link()")}}
+
{{htmlattrxref("href", "a", "<a href=\"url\">")}} (link to URL)
+
{{jsxref("String.prototype.small()")}} {{deprecated_inline}}
+
{{HTMLElement("small")}}
+
{{jsxref("String.prototype.strike()")}} {{deprecated_inline}}
+
{{HTMLElement("strike")}}
+
{{jsxref("String.prototype.sub()")}} {{deprecated_inline}}
+
{{HTMLElement("sub")}}
+
{{jsxref("String.prototype.sup()")}} {{deprecated_inline}}
+
{{HTMLElement("sup")}}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.5.3.1', 'String.prototype')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype', 'String.prototype')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype', 'String.prototype')}}{{Spec2('ESDraft')}} 
+ +

Browser compatibility

+ + + +

{{Compat("javascript.builtins.String.prototype")}}

+ +

See also

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/string/replace/index.html b/files/zh-tw/web/javascript/reference/global_objects/string/replace/index.html new file mode 100644 index 0000000000..1c42d9925f --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/string/replace/index.html @@ -0,0 +1,286 @@ +--- +title: String.prototype.replace() +slug: Web/JavaScript/Reference/Global_Objects/String/replace +translation_of: Web/JavaScript/Reference/Global_Objects/String/replace +--- +
{{JSRef}}
+ +

replace() 方法會傳回一個新字串,此新字串是透過將原字串與 pattern 比對,以 replacement 取代吻合處而生成。pattern 可以是字串或 {{jsxref("RegExp")}},而 replacement 可以是字串或函式(會在每一次匹配時被呼叫)。

+ +
+

備註:原始的字串會保持不變。

+
+ +

語法

+ +
str.replace(regexp|substr, newSubstr|function)
+ +

參數

+ +
+
regexp (pattern)
+
{{jsxref("RegExp")}} 的物件或文字。 被比對出來的部分將會被取代為 newSubStr 或是取代為 function 的回傳值。
+
substr (pattern)
+
要被 newSubStr 取代的 {{jsxref("String")}}。它被視為逐字字符串,並且不會被解釋為正則表達式。只會替換第一次出現。
+
newSubStr (replacement)
+
The {{jsxref("String")}} that replaces the substring specified by the specified regexp or substr parameter. A number of special replacement patterns are supported; see the "Specifying a string as a parameter" section below.
+
function (replacement)
+
A function to be invoked to create the new substring to be used to replace the matches to the given regexp or substr. The arguments supplied to this function are described in the "Specifying a function as a parameter" section below.
+
+ +

回傳值

+ +

A new string with some or all matches of a pattern replaced by a replacement.

+ +

描述

+ +

這個方法不會變更所呼叫的 {{jsxref("String")}}。它只會回傳新的字串。

+ +

To perform a global search and replace, include the g switch in the regular expression.

+ +

指定一個字串為參數

+ +

The replacement string can include the following special replacement patterns:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PatternInserts
$$Inserts a "$".
$&Inserts the matched substring.
$`Inserts the portion of the string that precedes the matched substring.
$'Inserts the portion of the string that follows the matched substring.
$nWhere n is a positive integer less than 100, inserts the nth parenthesized submatch string, provided the first argument was a {{jsxref("RegExp")}} object.
+ +

指定一個函式為參數

+ +

You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. (Note: the above-mentioned special replacement patterns do not apply in this case.) Note that the function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global.

+ +

The arguments to the function are as follows:

+ + + + + + + + + + + + + + + + + + + + + + + + +
Possible nameSupplied value
matchThe matched substring. (Corresponds to $& above.)
p1, p2, ...The nth parenthesized submatch string, provided the first argument to replace() was a {{jsxref("RegExp")}} object. (Corresponds to $1, $2, etc. above.) For example, if /(\a+)(\b+)/, was given, p1 is the match for \a+, and p2 for \b+.
offsetThe offset of the matched substring within the whole string being examined. (For example, if the whole string was 'abcd', and the matched substring was 'bc', then this argument will be 1.)
stringThe whole string being examined.
+ +

(The exact number of arguments will depend on whether the first argument was a {{jsxref("RegExp")}} object and, if so, how many parenthesized submatches it specifies.)

+ +

The following example will set newString to 'abc - 12345 - #$*%':

+ +
function replacer(match, p1, p2, p3, offset, string) {
+  // p1 is nondigits, p2 digits, and p3 non-alphanumerics
+  return [p1, p2, p3].join(' - ');
+}
+var newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
+console.log(newString);  // abc - 12345 - #$*%
+
+ +

範例

+ +

replace() 中定義正則表示式

+ +

下例的正規表達式被定義為 replace()、並包含了忽略大小寫的 flag。

+ +
var str = 'Twas the night before Xmas...';
+var newstr = str.replace(/xmas/i, 'Christmas');
+console.log(newstr);  // Twas the night before Christmas...
+
+ +

上例會顯示「Twas the night before Christmas...」

+ +

使用 globalignore 來配合 replace()

+ +

Global replace can only be done with a regular expression. In the following example, the regular expression includes the global and ignore case flags which permits replace() to replace each occurrence of 'apples' in the string with 'oranges'.

+ +
var re = /apples/gi;
+var str = 'Apples are round, and apples are juicy.';
+var newstr = str.replace(re, 'oranges');
+console.log(newstr);  // oranges are round, and oranges are juicy.
+
+ +

上例會顯示「oranges are round, and oranges are juicy」。

+ +

替換字串中的單字

+ +

下例程式將切換字串內的單字。對 replacement text 而言,程式會使用 $1 and $2 的 replacement pattern。

+ +
var re = /(\w+)\s(\w+)/;
+var str = 'John Smith';
+var newstr = str.replace(re, '$2, $1');
+console.log(newstr);  // Smith, John
+
+ +

上例會顯示「Smith, John」。

+ +

使用行內函式來修改匹配的字元

+ +

In this example, all occurrences of capital letters in the string are converted to lower case, and a hyphen is inserted just before the match location. The important thing here is that additional operations are needed on the matched item before it is given back as a replacement.

+ +

The replacement function accepts the matched snippet as its parameter, and uses it to transform the case and concatenate the hyphen before returning.

+ +
function styleHyphenFormat(propertyName) {
+  function upperToHyphenLower(match, offset, string) {
+    return (offset ? '-' : '') + match.toLowerCase();
+  }
+  return propertyName.replace(/[A-Z]/g, upperToHyphenLower);
+}
+
+ +

Given styleHyphenFormat('borderTop'), this returns 'border-top'.

+ +

Because we want to further transform the result of the match before the final substitution is made, we must use a function. This forces the evaluation of the match prior to the {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}} method. If we had tried to do this using the match without a function, the {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}} would have no effect.

+ +
var newString = propertyName.replace(/[A-Z]/g, '-' + '$&'.toLowerCase());  // won't work
+
+ +

This is because '$&'.toLowerCase() would be evaluated first as a string literal (resulting in the same '$&') before using the characters as a pattern.

+ +

將華氏溫度置換成攝氏溫度

+ +

The following example replaces a Fahrenheit degree with its equivalent Celsius degree. The Fahrenheit degree should be a number ending with F. The function returns the Celsius number ending with C. For example, if the input number is 212F, the function returns 100C. If the number is 0F, the function returns -17.77777777777778C.

+ +

The regular expression test checks for any number that ends with F. The number of Fahrenheit degree is accessible to the function through its second parameter, p1. The function sets the Celsius number based on the Fahrenheit degree passed in a string to the f2c() function. f2c() then returns the Celsius number. This function approximates Perl's s///e flag.

+ +
function f2c(x) {
+  function convert(str, p1, offset, s) {
+    return ((p1 - 32) * 5/9) + 'C';
+  }
+  var s = String(x);
+  var test = /(-?\d+(?:\.\d*)?)F\b/g;
+  return s.replace(test, convert);
+}
+
+ +

利用行內函式及正則表示式來避免使用 for 迴圈

+ +

The following example takes a string pattern and converts it into an array of objects.

+ +

Input:

+ +

A string made out of the characters x, - and _

+ +
x-x_
+x---x---x---x---
+x-xxx-xx-x-
+x_x_x___x___x___
+
+ +

Output:

+ +

An array of objects. An 'x' denotes an 'on' state, a '-' (hyphen) denotes an 'off' state and an '_' (underscore) denotes the length of an 'on' state.

+ +
[
+  { on: true, length: 1 },
+  { on: false, length: 1 },
+  { on: true, length: 2 }
+  ...
+]
+
+ +

Snippet:

+ +
var str = 'x-x_';
+var retArr = [];
+str.replace(/(x_*)|(-)/g, function(match, p1, p2) {
+  if (p1) { retArr.push({ on: true, length: p1.length }); }
+  if (p2) { retArr.push({ on: false, length: 1 }); }
+});
+
+console.log(retArr);
+
+ +

This snippet generates an array of 3 objects in the desired format without using a for loop.

+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態註解
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.4.11', 'String.prototype.replace')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.replace', 'String.prototype.replace')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.replace', 'String.prototype.replace')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.String.replace")}}

+ +

Firefox-specific notes

+ + + +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/string/tolowercase/index.html b/files/zh-tw/web/javascript/reference/global_objects/string/tolowercase/index.html new file mode 100644 index 0000000000..35b9dc71bc --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/string/tolowercase/index.html @@ -0,0 +1,77 @@ +--- +title: String.prototype.toLowerCase() +slug: Web/JavaScript/Reference/Global_Objects/String/toLowerCase +translation_of: Web/JavaScript/Reference/Global_Objects/String/toLowerCase +--- +
{{JSRef}}
+ +

toLowerCase() 函式会回传将字符串转换为英文小写字母后的结果。

+ +
{{EmbedInteractiveExample("pages/js/string-tolowercase.html")}}
+ + + +

语法

+ +
str.toLowerCase()
+ +

回传值

+ +

回传一组将原字串英文内容转换成英文小写字母后的结果。

+ +

描述

+ +

The toLowerCase() 函式会回传一组将原字符串英文内容转换成英文小写字母后的结果。 toLowerCase() 并不会影响到原字符串 str 的内容值。

+ +

范例

+ +

使用toLowerCase()

+ +
console.log('ALPHABET'.toLowerCase()); // 'alphabet'
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态注解
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.4.16', 'String.prototype.toLowerCase')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.prototype.tolowercase', 'String.prototype.toLowerCase')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-string.prototype.tolowercase', 'String.prototype.toLowerCase')}}{{Spec2('ESDraft')}}
+ +

浏览器相容性

+ + + +

{{Compat("javascript.builtins.String.toLowerCase")}}

+ +

参考

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/typedarray/index.html b/files/zh-tw/web/javascript/reference/global_objects/typedarray/index.html new file mode 100644 index 0000000000..f37e7ac069 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/typedarray/index.html @@ -0,0 +1,268 @@ +--- +title: TypedArray +slug: Web/JavaScript/Reference/Global_Objects/TypedArray +tags: + - JavaScript + - TypedArray + - TypedArrays +translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray +--- +
{{JSRef}}
+ +

TypedArray 物件表示了一個底層 ArrayBuffer 的類陣列(array-like)視圖,它能以限定的型別解讀、修改 ArrayBuffer。但並沒有名為 TypedArray 的內建物件,TypedArray 也不存在可直接呼叫的建構式。真正能夠使用的是幾個原型繼承自 TypedArray 的內建物件,它們可以建立限定成員型別的物件實體來操作 ArrayBuffer。這些 TypedArray 型別的物件僅為視圖,並不會存放資料,所有的資料皆實際儲存於 ArrayBuffer 物件當中。以下將說明每種限定成員型別之 TypedArray 的共同屬性與方法。

+ +
{{EmbedInteractiveExample("pages/js/typedarray-constructor.html")}}
+ + + +

語法

+ +
new TypedArray(length);
+new TypedArray(typedArray);
+new TypedArray(object);
+new TypedArray(buffer [, byteOffset [, length]]);
+
+where TypedArray() is one of:
+
+Int8Array();
+Uint8Array();
+Uint8ClampedArray();
+Int16Array();
+Uint16Array();
+Int32Array();
+Uint32Array();
+Float32Array();
+Float64Array();
+
+ +

參數

+ +
+
length
+
When called with a length argument, a typed array containing length zeroes is created.
+
typedArray
+
When called with a typedArray argument, which can be an object of any of the typed array types (such as Int32Array), the typedArray gets copied into a new typed array. Each value in typedArray is converted to the corresponding type of the constructor before being copied into the new array.
+
object
+
When called with an object argument, a new typed array is created as if by the TypedArray.from() method.
+
buffer, byteOffset, length
+
When called with a buffer, and optionally a byteOffset and a length argument, a new typed array view is created that views the specified {{jsxref("ArrayBuffer")}}. The byteOffset and length parameters specify the memory range that will be exposed by the typed array view.  If both are omitted, all of buffer is viewed; if only length is omitted, the remainder of buffer is viewed.
+
+ +

說明

+ +

ECMAScript 2015 defines a TypedArray constructor that serves as the [[Prototype]] of all TypedArray constructors.  This constructor is not directly exposed: there is no global %TypedArray% or TypedArray property.  It is only directly accessible through Object.getPrototypeOf(Int8Array) and similar.  All TypedArrays constructors inherit common properties from the %TypedArray% constructor function.  Additionally, all typed array prototypes (TypedArray.prototype) have %TypedArray%.prototype as their [[Prototype]].

+ +

The %TypedArray% constructor on its own is not particularly useful.  Calling it or using it in a new expression will throw a TypeError, except when used during object creation in JS engines that support subclassing.  There are at present no such engines, so %TypedArray% is only useful to polyfill functions or properties onto all TypedArray constructors.

+ +

When creating an instance of a TypedArray (e.g. Int8Array), an array buffer is created internally in memory or, if an ArrayBuffer object is given as constructor argument, then this is used instead.  The buffer address is saved as an internal property of the instance and all the methods of %TypedArray%.prototype, i.e. set value and get value etc., operate on that array buffer address.

+ +

Property access

+ +

You can reference elements in the array using standard array index syntax (that is, using bracket notation). However, getting or setting indexed properties on typed arrays will not search in the prototype chain for this property, even when the indices are out of bound. Indexed properties will consult the {{jsxref("ArrayBuffer")}} and will never look at object properties. You can still use named properties, just like with all objects.

+ +
// Setting and getting using standard array syntax
+var int16 = new Int16Array(2);
+int16[0] = 42;
+console.log(int16[0]); // 42
+
+// Indexed properties on prototypes are not consulted (Fx 25)
+Int8Array.prototype[20] = 'foo';
+(new Int8Array(32))[20]; // 0
+// even when out of bound
+Int8Array.prototype[20] = 'foo';
+(new Int8Array(8))[20]; // undefined
+// or with negative integers
+Int8Array.prototype[-1] = 'foo';
+(new Int8Array(8))[-1]; // undefined
+
+// Named properties are allowed, though (Fx 30)
+Int8Array.prototype.foo = 'bar';
+(new Int8Array(32)).foo; // "bar"
+ +

TypedArray 物件

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
TypeValue RangeSize in bytesDescriptionWeb IDL typeEquivalent C type
{{jsxref("Int8Array")}}-128 to 12718-bit two's complement signed integerbyteint8_t
{{jsxref("Uint8Array")}}0 to 25518-bit unsigned integeroctetuint8_t
{{jsxref("Uint8ClampedArray")}}0 to 25518-bit unsigned integer (clamped)octetuint8_t
{{jsxref("Int16Array")}}-32768 to 32767216-bit two's complement signed integershortint16_t
{{jsxref("Uint16Array")}}0 to 65535216-bit unsigned integerunsigned shortuint16_t
{{jsxref("Int32Array")}}-2147483648 to 2147483647432-bit two's complement signed integerlongint32_t
{{jsxref("Uint32Array")}}0 to 4294967295432-bit unsigned integerunsigned longuint32_t
{{jsxref("Float32Array")}}1.2x10-38 to 3.4x1038432-bit IEEE floating point number ( 7 significant digits e.g. 1.1234567)unrestricted floatfloat
{{jsxref("Float64Array")}}5.0x10-324 to 1.8x10308864-bit IEEE floating point number (16 significant digits e.g. 1.123...15)unrestricted doubledouble
+ +

屬性

+ +
+
{{jsxref("TypedArray.BYTES_PER_ELEMENT")}}
+
Returns a number value of the element size for the different typed array objects.
+
TypedArray.length
+
Length property whose value is 0.
+
{{jsxref("TypedArray.name")}}
+
Returns the string value of the constructor name. E.g "Int8Array".
+
{{jsxref("TypedArray.@@species", "get TypedArray[@@species]")}}
+
The constructor function that is used to create derived objects.
+
{{jsxref("TypedArray.prototype")}}
+
Prototype for the TypedArray objects.
+
+ +

方法

+ +
+
{{jsxref("TypedArray.from()")}}
+
Creates a new typed array from an array-like or iterable object. See also {{jsxref("Array.from()")}}.
+
{{jsxref("TypedArray.of()")}}
+
Creates a new typed array with a variable number of arguments. See also {{jsxref("Array.of()")}}.
+
+ +

TypedArray 原型

+ +

All TypedArrays inherit from {{jsxref("TypedArray.prototype")}}.

+ +

屬性

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/TypedArray/prototype','Properties')}}

+ +

方法

+ +

{{page('en-US/Web/JavaScript/Reference/Global_Objects/TypedArray/prototype','Methods')}}

+ +

Methods Polyfill

+ +

Many of the methods used in Typed Arrays can be polyfilled using the methods present in regular Javascript Arrays. The following snippet of JavaScript demonstrates how you might polyfill any missing Typed Array methods.

+ +
var typedArrayTypes = [Int8Array, Uint8Array, Uint8ClampedArray, Int16Array,
+          Uint16Array, ​​​Int32Array, Uint32Array, ​​​Float32Array, Float64Array];
+
+for (var k in typedArrayTypes)
+    for (var v in Array.prototype)
+        if (Array.prototype.hasOwnProperty(v) &&
+          !typedArrayTypes[k].prototype.hasOwnProperty(v))
+            typedArrayTypes[k].prototype[v] = Array.prototype[v];
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Typed Array')}}{{Spec2('Typed Array')}}Defined as TypedArray and ArrayBufferView interface with typed array view types. Superseded by ECMAScript 6.
{{SpecName('ES6', '#sec-typedarray-objects', 'TypedArray Objects')}}{{Spec2('ES6')}}Initial definition in an ECMA standard. Specified behaviour for indexed and named properties. Specified that new is required.
{{SpecName('ESDraft', '#sec-typedarray-objects', 'TypedArray Objects')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.TypedArray")}}

+ +

相容性備註

+ +

Starting with ECMAScript 2015, TypedArray constructors require to be constructed with a {{jsxref("Operators/new", "new")}} operator. Calling a TypedArray constructor as a function without new, will throw a {{jsxref("TypeError")}} from now on.

+ +
var dv = Int8Array([1, 2, 3]);
+// TypeError: calling a builtin Int8Array constructor
+// without new is forbidden
+ +
var dv = new Int8Array([1, 2, 3]);
+ +

參見

+ + diff --git a/files/zh-tw/web/javascript/reference/global_objects/undefined/index.html b/files/zh-tw/web/javascript/reference/global_objects/undefined/index.html new file mode 100644 index 0000000000..f352c84d71 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/undefined/index.html @@ -0,0 +1,136 @@ +--- +title: undefined +slug: Web/JavaScript/Reference/Global_Objects/undefined +tags: + - JavaScript +translation_of: Web/JavaScript/Reference/Global_Objects/undefined +--- +
{{jsSidebar("Objects")}}
+ +

The global undefined property represents the primitive value {{Glossary("Undefined", "undefined")}}. It is one of JavaScript's {{Glossary("Primitive", "primitive types")}}.

+ +

{{js_property_attributes(0,0,0)}}

+ +
{{EmbedInteractiveExample("pages/js/globalprops-undefined.html")}}
+ + +

語法

+ +
undefined
+ +

描述

+ +

undefined is a property of the global object; i.e., it is a variable in global scope. The initial value of undefined is the primitive value {{Glossary("Undefined", "undefined")}}.

+ +

In modern browsers (JavaScript 1.8.5 / Firefox 4+), undefined is a non-configurable, non-writable property per the ECMAScript 5 specification. Even when this is not the case, avoid overriding it.

+ +

A variable that has not been assigned a value is of type undefined. A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not {{jsxref("Statements/return", "returned")}}.

+ +
+

While it is possible to use it as an {{Glossary("Identifier", "identifier")}} (variable name) in any scope other than the global scope (because undefined is not a {{jsxref("Reserved_Words", "reserved word")}}), doing so is a very bad idea that will make your code difficult to maintain and debug.

+ +
//DON'T DO THIS
+
+// logs "foo string"
+(function() { var undefined = 'foo'; console.log(undefined, typeof undefined); })();
+
+// logs "foo string"
+(function(undefined) { console.log(undefined, typeof undefined); })('foo');
+
+
+ +

範例

+ +

Strict equality and undefined

+ +

You can use undefined and the strict equality and inequality operators to determine whether a variable has a value. In the following code, the variable x is not defined, and the if statement evaluates to true.

+ +
var x;
+if (x === undefined) {
+   // these statements execute
+}
+else {
+   // these statements do not execute
+}
+
+ +
+

備註:The strict equality operator rather than the standard equality operator must be used here, because x == undefined also checks whether x is null, while strict equality doesn't. null is not equivalent to undefined. See {{jsxref("Operators/Comparison_Operators", "comparison operators")}} for details.

+
+ +

Typeof operator and undefined

+ +

Alternatively, {{jsxref("Operators/typeof", "typeof")}} can be used:

+ +
var x;
+if (typeof x === 'undefined') {
+   // these statements execute
+}
+
+ +

One reason to use {{jsxref("Operators/typeof", "typeof")}} is that it does not throw an error if the variable has not been declared.

+ +
// x has not been declared before
+if (typeof x === 'undefined') { // evaluates to true without errors
+   // these statements execute
+}
+
+if (x === undefined) { // throws a ReferenceError
+
+}
+
+ +

However, this kind of technique should be avoided. JavaScript is a statically scoped language, so knowing if a variable is declared can be read by seeing whether it is declared in an enclosing context. The only exception is the global scope, but the global scope is bound to the global object, so checking the existence of a variable in the global context can be done by checking the existence of a property on the global object (using the {{jsxref("Operators/in", "in")}} operator, for instance).

+ +

Void operator and undefined

+ +

The {{jsxref("Operators/void", "void")}} operator is a third alternative.

+ +
var x;
+if (x === void 0) {
+   // these statements execute
+}
+
+// y has not been declared before
+if (y === void 0) {
+   // throws a - Uncaught ReferenceError: y is not defined
+}
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1', '#sec-4.3.9', 'undefined')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.1.1.3', 'undefined')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-undefined', 'undefined')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-undefined', 'undefined')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.builtins.undefined")}}

diff --git a/files/zh-tw/web/javascript/reference/global_objects/urierror/index.html b/files/zh-tw/web/javascript/reference/global_objects/urierror/index.html new file mode 100644 index 0000000000..be0bb96d13 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/global_objects/urierror/index.html @@ -0,0 +1,131 @@ +--- +title: URIError +slug: Web/JavaScript/Reference/Global_Objects/URIError +translation_of: Web/JavaScript/Reference/Global_Objects/URIError +--- +
{{JSRef}}
+ +

URIError 物件在全域的URI處理函式被錯誤使用時作為一個錯誤被拋出。

+ +

語法

+ +
new URIError([message[, fileName[, lineNumber]]])
+ +

參數

+ +
+
message
+
可選。具人類可讀性的錯誤說明
+
fileName {{non-standard_inline}}
+
可選。包含造成錯誤發生的程式碼的檔案名稱
+
lineNumber {{non-standard_inline}}
+
可選。造成錯誤發生的程式碼行號
+
+ +

說明

+ +

URIError 在全域的URI處理函式被傳入了一個錯誤編碼的URI時被拋出。

+ +

屬性

+ +
+
{{jsxref("URIError.prototype")}}
+
允許對一個 URIError 物件增加其屬性。
+
+ +

方法

+ +

普遍的 URIError 自身沒有包含方法,儘管他的確從原型鍊中繼承了一些。

+ +

URIError 物件實體

+ +

屬性

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError/prototype', 'Properties')}}
+ +

方法

+ +
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError/prototype', 'Methods')}}
+ +

範例

+ +

Catch 一個 URIError

+ +
try {
+  decodeURIComponent('%');
+} catch (e) {
+  console.log(e instanceof URIError); // true
+  console.log(e.message);             // "malformed URI sequence"
+  console.log(e.name);                // "URIError"
+  console.log(e.fileName);            // "Scratchpad/1"
+  console.log(e.lineNumber);          // 2
+  console.log(e.columnNumber);        // 2
+  console.log(e.stack);               // "@Scratchpad/2:2:3\n"
+}
+
+ +

生成一個 URIError

+ +
try {
+  throw new URIError('Hello', 'someFile.js', 10);
+} catch (e) {
+  console.log(e instanceof URIError); // true
+  console.log(e.message);             // "Hello"
+  console.log(e.name);                // "URIError"
+  console.log(e.fileName);            // "someFile.js"
+  console.log(e.lineNumber);          // 10
+  console.log(e.columnNumber);        // 0
+  console.log(e.stack);               // "@Scratchpad/2:2:9\n"
+}
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態
{{SpecName('ES3', '#sec-15.11.6.6', 'URIError')}}{{Spec2('ES3')}}Initial definition
{{SpecName('ES5.1', '#sec-15.11.6.6', 'URIError')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-native-error-types-used-in-this-standard-urierror', 'URIError')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-native-error-types-used-in-this-standard-urierror', 'URIError')}}{{Spec2('ESDraft')}} 
+ +

瀏覽器相容性

+ +
+ + +

{{Compat("javascript.builtins.URIError")}}

+
+ +

另見

+ + -- cgit v1.2.3-54-g00ecf