diff --git a/.prettierignore b/.prettierignore index a4e7a19eb91e30..fd45daabb3ceb7 100644 --- a/.prettierignore +++ b/.prettierignore @@ -33,6 +33,3 @@ build/ # zh-cn /files/zh-cn/**/*.md - -# zh-tw -/files/zh-tw/web/javascript/reference/global_objects/[p-t]*/**/*.md diff --git a/files/zh-tw/web/javascript/reference/global_objects/parseint/index.md b/files/zh-tw/web/javascript/reference/global_objects/parseint/index.md index 65fcae47659a7d..ab583b2dbeee67 100644 --- a/files/zh-tw/web/javascript/reference/global_objects/parseint/index.md +++ b/files/zh-tw/web/javascript/reference/global_objects/parseint/index.md @@ -11,7 +11,7 @@ slug: Web/JavaScript/Reference/Global_Objects/parseInt ## 語法 -```plain +```js-nolint parseInt(string, radix); ``` @@ -72,7 +72,7 @@ parseInt("12", 13); ```js parseInt("Hello", 8); // 根本不是數字 -parseInt("546", 2); // 在二進位無效 +parseInt("546", 2); // 在二進位無效 ``` 以下的範例,回傳的值均為 **`-15`**: @@ -81,7 +81,7 @@ parseInt("546", 2); // 在二進位無效 parseInt("-F", 16); parseInt("-0F", 16); parseInt("-0XF", 16); -parseInt(-15.1, 10) +parseInt(-15.1, 10); parseInt(" -17", 8); parseInt(" -15", 10); parseInt("-1111", 2); @@ -124,23 +124,22 @@ Many implementations have not adopted this behavior as of 2013, and because olde ## 嚴謹的解析 function -有的時候,使用更嚴謹的 code 能夠更精確地轉換整數值。 Regular expressions 可以幫你: +有的時候,使用更嚴謹的 code 能夠更精確地轉換整數值。Regular expression 可以幫你: ```js filterInt = function (value) { - if(/^(\-|\+)?([0-9]+|Infinity)$/.test(value)) - return Number(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 +}; + +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 ``` ## 規範 @@ -151,7 +150,7 @@ console.log(filterInt('1.61803398875')); // NaN {{Compat}} -## 延伸閱讀 +## 參見 - {{jsxref("Global_Objects/parseFloat", "parseFloat()")}} - {{jsxref("Number.parseFloat()")}} diff --git a/files/zh-tw/web/javascript/reference/global_objects/promise/all/index.md b/files/zh-tw/web/javascript/reference/global_objects/promise/all/index.md index 9b560b764f0a57..6eb288112510e9 100644 --- a/files/zh-tw/web/javascript/reference/global_objects/promise/all/index.md +++ b/files/zh-tw/web/javascript/reference/global_objects/promise/all/index.md @@ -9,7 +9,7 @@ slug: Web/JavaScript/Reference/Global_Objects/Promise/all ## 語法 -```plain +```js Promise.all(iterable); ``` @@ -42,10 +42,10 @@ Promise.all(iterable); var p1 = Promise.resolve(3); var p2 = 1337; var p3 = new Promise((resolve, reject) => { - setTimeout(resolve, 100, 'foo'); + setTimeout(resolve, 100, "foo"); }); -Promise.all([p1, p2, p3]).then(values => { +Promise.all([p1, p2, p3]).then((values) => { console.log(values); // [3, 1337, "foo"] }); ``` @@ -54,17 +54,17 @@ Promise.all([p1, p2, p3]).then(values => { ```js // this will be counted as if the iterable passed is empty, so it gets fulfilled -var p = Promise.all([1,2,3]); +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)]); +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)]); +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); +setTimeout(function () { + console.log(p); + console.log(p2); + console.log(p3); }); // logs @@ -87,9 +87,9 @@ var p = Promise.all(resolvedPromisesArray); 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); +setTimeout(function () { + console.log("the stack is now empty"); + console.log(p); }); // logs, in order: @@ -104,9 +104,9 @@ setTimeout(function(){ 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); +setTimeout(function () { + console.log("the stack is now empty"); + console.log(p); }); // logs @@ -121,10 +121,10 @@ setTimeout(function(){ 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); +console.log(p2); +setTimeout(function () { + console.log("the stack is now empty"); + console.log(p2); }); // logs @@ -140,36 +140,41 @@ setTimeout(function(){ ```js var p1 = new Promise((resolve, reject) => { - setTimeout(resolve, 1000, 'one'); + setTimeout(resolve, 1000, "one"); }); var p2 = new Promise((resolve, reject) => { - setTimeout(resolve, 2000, 'two'); + setTimeout(resolve, 2000, "two"); }); var p3 = new Promise((resolve, reject) => { - setTimeout(resolve, 3000, 'three'); + setTimeout(resolve, 3000, "three"); }); var p4 = new Promise((resolve, reject) => { - setTimeout(resolve, 4000, 'four'); + setTimeout(resolve, 4000, "four"); }); var p5 = new Promise((resolve, reject) => { - reject('reject'); + reject("reject"); }); -Promise.all([p1, p2, p3, p4, p5]).then(values => { - console.log(values); -}, reason => { - console.log(reason) -}); +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) -}); +Promise.all([p1, p2, p3, p4, p5]) + .then((values) => { + console.log(values); + }) + .catch((reason) => { + console.log(reason); + }); //From console: //"reject" diff --git a/files/zh-tw/web/javascript/reference/global_objects/promise/catch/index.md b/files/zh-tw/web/javascript/reference/global_objects/promise/catch/index.md index 39da4abe4c8e1c..c458967c3c2079 100644 --- a/files/zh-tw/web/javascript/reference/global_objects/promise/catch/index.md +++ b/files/zh-tw/web/javascript/reference/global_objects/promise/catch/index.md @@ -9,11 +9,11 @@ slug: Web/JavaScript/Reference/Global_Objects/Promise/catch ## 語法 -```plain +```js p.catch(onRejected); -p.catch(function(reason) { - // rejection +p.catch(function (reason) { + // rejection }); ``` @@ -36,25 +36,30 @@ p.catch(function(reason) { ```js // overriding original Promise.prototype.then/catch just to add some logs -(function(Promise){ - var originalThen = Promise.prototype.then; - var originalCatch = Promise.prototype.catch; - - Promise.prototype.then = function(){ - console.log('> > > > > > called .then on %o with arguments: %o', this, arguments); - return originalThen.apply(this, arguments); - }; - Promise.prototype.catch = function(){ - console.log('> > > > > > called .catch on %o with arguments: %o', this, arguments); - return originalCatch.apply(this, arguments); - }; - +(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(){}); +Promise.resolve().catch(function XXX() {}); // logs: // > > > > > > called .catch on Promise{} with arguments: Arguments{1} [0: function XXX()] @@ -70,65 +75,75 @@ Promise.resolve().catch(function XXX(){}); ### 使用及串接 `catch` 方法 ```js -var p1 = new Promise(function(resolve, reject) { - resolve('Success'); +var p1 = new Promise(function (resolve, reject) { + resolve("Success"); }); -p1.then(function(value) { +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'); -}); + 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) { +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'); -}); + return Promise.reject("oh, no!"); +}) + .catch(function (e) { + console.log(e); // "oh, no!" + }) + .then( + function () { + console.log("after a catch the chain is restored"); + }, + function () { + console.log("Not fired due to the catch"); + } + ); ``` ### 拋出例外時的陷阱 ```js // Throwing an error will call the catch method most of the time -var p1 = new Promise(function(resolve, reject) { - throw 'Uh-oh!'; +var p1 = new Promise(function (resolve, reject) { + throw "Uh-oh!"; }); -p1.catch(function(e) { +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!'; +var p2 = new Promise(function (resolve, reject) { + setTimeout(function () { + throw "Uncaught Exception!"; }, 1000); }); -p2.catch(function(e) { +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) { +var p3 = new Promise(function (resolve, reject) { resolve(); - throw 'Silenced Exception!'; + throw "Silenced Exception!"; }); -p3.catch(function(e) { - console.log(e); // This is never called +p3.catch(function (e) { + console.log(e); // This is never called }); ``` @@ -139,18 +154,21 @@ p3.catch(function(e) { var p1 = Promise.resolve("calling next"); var p2 = p1.catch(function (reason) { - //This is never called - console.log("catch p1!"); - console.log(reason); + //This is never called + console.log("catch p1!"); + console.log(reason); }); -p2.then(function (value) { +p2.then( + function (value) { console.log("next promise's onFulfilled"); /* next promise's onFulfilled */ console.log(value); /* calling next */ -}, function (reason) { + }, + function (reason) { console.log("next promise's onRejected"); console.log(reason); -}); + } +); ``` ## 規範 diff --git a/files/zh-tw/web/javascript/reference/global_objects/promise/finally/index.md b/files/zh-tw/web/javascript/reference/global_objects/promise/finally/index.md index a45dbfd937e834..e722100c9edfc3 100644 --- a/files/zh-tw/web/javascript/reference/global_objects/promise/finally/index.md +++ b/files/zh-tw/web/javascript/reference/global_objects/promise/finally/index.md @@ -11,11 +11,11 @@ slug: Web/JavaScript/Reference/Global_Objects/Promise/finally ## Syntax -```plain +```js p.finally(onFinally); -p.finally(function() { - // settled(fulfilled 或 rejected) +p.finally(function () { + // settled(fulfilled 或 rejected) }); ``` @@ -40,34 +40,41 @@ p.finally(function() { - 與 `Promise.resolve(2).then(() => {}, () => {})`(將被 resolved 為`undefined`)不同,`Promise.resolve(2).finally(() => {})` 將被 resolved 為`2`。 - 同樣的,與 `Promise.reject(3).then(() => {}, () => {})`(將 fulfilled 為`undefined`)不同,`Promise.reject(3).finally(() => {})` 將被 rejected 為`3`。 -> **備註:** 在 finally 回呼中使用 throw (或回傳 rejected promise)會導致新的 promise 被 reject , reject 的原因則是呼叫 throw() 時所指定的值。 +> **備註:** 在 finally 回呼中使用 throw(或回傳 rejected promise)會導致新的 promise 被 reject,reject 的原因則是呼叫 throw() 時所指定的值。 -## Examples +## 範例 ```js let isLoading = true; -fetch(myRequest).then(function(response) { +fetch(myRequest) + .then(function (response) { var contentType = response.headers.get("content-type"); - if(contentType && contentType.includes("application/json")) { + 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; }); + .then(function (json) { + /* process your JSON further */ + }) + .catch(function (error) { + console.log(error); + }) + .finally(function () { + isLoading = false; + }); ``` -## Specifications +## 規範 {{Specifications}} -## Browser compatibility +## 瀏覽器相容性 {{Compat}} -## See also +## 參見 - {{jsxref("Promise")}} - {{jsxref("Promise.prototype.then()")}} diff --git a/files/zh-tw/web/javascript/reference/global_objects/promise/index.md b/files/zh-tw/web/javascript/reference/global_objects/promise/index.md index caa5962359f323..56a091f3150386 100644 --- a/files/zh-tw/web/javascript/reference/global_objects/promise/index.md +++ b/files/zh-tw/web/javascript/reference/global_objects/promise/index.md @@ -104,7 +104,7 @@ function myAsyncFunction(url) { xhr.onerror = () => reject(xhr.statusText); xhr.send(); }); -}; +} ``` ## 範例 @@ -116,7 +116,7 @@ let myFirstPromise = new Promise((resolve, reject) => { // 當非同步作業成功時,呼叫 resolve(...),而失敗時則呼叫 reject(...)。 // 在這個例子中,使用 setTimeout(...) 來模擬非同步程式碼。 // 在實務中,您將可能使用像是 XHR 或者一個 HTML5 API. - setTimeout(function(){ + setTimeout(function () { resolve("Success!"); // Yay!非常順利! }, 250); }); @@ -140,48 +140,58 @@ myFirstPromise.then((successMessage) => { promise 的實現值單純地經由一個實現回呼函式 {{jsxref("Promise.prototype.then()","p1.then()")}} 被印出。下以一些文字紀錄來展現方法中同步的與非同步處理 promise 的部分是如何分離彼此。 ```js -'use strict'; +"use strict"; var promiseCount = 0; function testPromise() { - let thisPromiseCount = ++promiseCount; - - let log = document.getElementById('log'); - log.insertAdjacentHTML('beforeend', thisPromiseCount + - ') Started (Sync code started)
'); - - // 建立一個新的 promise:此 promise 承諾一個數值計數, 由 1 開始(等待約 2 秒) - let p1 = new Promise( - // 這個解決器函數(resolver function)呼叫實現或 - // 拒絕 promise。 - (resolve, reject) => { - log.insertAdjacentHTML('beforeend', thisPromiseCount + - ') Promise started (Async code started)
'); - // 在此例子單純用來產生非同步特性。 - 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 (Async code terminated)
'); - }) - .catch( - // 印出失敗訊息(rejection reason) - (reason) => { - console.log('Handle rejected promise ('+reason+') here.'); - }); - - log.insertAdjacentHTML('beforeend', thisPromiseCount + - ') Promise made (Sync code terminated)
'); + let thisPromiseCount = ++promiseCount; + + let log = document.getElementById("log"); + log.insertAdjacentHTML( + "beforeend", + thisPromiseCount + ") Started (Sync code started)
" + ); + + // 建立一個新的 promise:此 promise 承諾一個數值計數, 由 1 開始(等待約 2 秒) + let p1 = new Promise( + // 這個解決器函數(resolver function)呼叫實現或 + // 拒絕 promise。 + (resolve, reject) => { + log.insertAdjacentHTML( + "beforeend", + thisPromiseCount + + ") Promise started (Async code started)
" + ); + // 在此例子單純用來產生非同步特性。 + 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 (Async code terminated)
" + ); + } + ).catch( + // 印出失敗訊息(rejection reason) + (reason) => { + console.log("Handle rejected promise (" + reason + ") here."); + } + ); + + log.insertAdjacentHTML( + "beforeend", + thisPromiseCount + + ") Promise made (Sync code terminated)
" + ); } ``` @@ -190,10 +200,11 @@ function testPromise() { ```js if ("Promise" in window) { let btn = document.getElementById("btn"); - btn.addEventListener("click",testPromise); + btn.addEventListener("click", testPromise); } else { - log = document.getElementById('log'); - log.innerHTML = "Live example not available as your browser doesn't support the Promise interface."; + log = document.getElementById("log"); + log.innerHTML = + "Live example not available as your browser doesn't support the Promise interface."; } ``` diff --git a/files/zh-tw/web/javascript/reference/global_objects/promise/race/index.md b/files/zh-tw/web/javascript/reference/global_objects/promise/race/index.md index facbd79cd9ed29..7ba26152056181 100644 --- a/files/zh-tw/web/javascript/reference/global_objects/promise/race/index.md +++ b/files/zh-tw/web/javascript/reference/global_objects/promise/race/index.md @@ -9,7 +9,7 @@ slug: Web/JavaScript/Reference/Global_Objects/Promise/race ## 語法 -```plain +```js Promise.race(iterable); ``` @@ -30,7 +30,7 @@ Promise.race(iterable); ### `Promise.race` 的非同步性質 -以下例子演示了 `Promise.race` `的非同步性質:` +以下例子演示了 `Promise.race` 的非同步性質: ```js // we are passing as argument an array of promises that are already resolved, @@ -42,9 +42,9 @@ var p = Promise.race(resolvedPromisesArray); 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); +setTimeout(function () { + console.log("the stack is now empty"); + console.log(p); }); // logs, in order: @@ -58,9 +58,9 @@ setTimeout(function(){ ```js var foreverPendingPromise = Promise.race([]); console.log(foreverPendingPromise); -setTimeout(function(){ - console.log('the stack is now empty'); - console.log(foreverPendingPromise); +setTimeout(function () { + console.log("the stack is now empty"); + console.log(foreverPendingPromise); }); // logs, in order: @@ -82,10 +82,10 @@ 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); +setTimeout(function () { + console.log("the stack is now empty"); + console.log(p); + console.log(p2); }); // logs, in order: @@ -96,48 +96,54 @@ setTimeout(function(){ // Promise { : "fulfilled", : "non-Promise value" } ``` -### 使用 `Promise.race` – 及 [`setTimeout`](/zh-TW/docs/Web/API/setTimeout) 的範例 +### 使用 `Promise.race` 及 `setTimeout` 的範例 ```js -var p1 = new Promise(function(resolve, reject) { - setTimeout(resolve, 500, 'one'); +var p1 = new Promise(function (resolve, reject) { + setTimeout(resolve, 500, "one"); }); -var p2 = new Promise(function(resolve, reject) { - setTimeout(resolve, 100, 'two'); +var p2 = new Promise(function (resolve, reject) { + setTimeout(resolve, 100, "two"); }); -Promise.race([p1, p2]).then(function(value) { +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'); +var p3 = new Promise(function (resolve, reject) { + setTimeout(resolve, 100, "three"); }); - -Promise.race([p3, p4]).then(function(value) { - console.log(value); // "three" - // p3 is faster, so it resolves -}, function(reason) { - // Not called +var p4 = new Promise(function (resolve, reject) { + setTimeout(reject, 500, "four"); }); -var p5 = new Promise(function(resolve, reject) { - setTimeout(resolve, 500, 'five'); +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'); +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 -}); +Promise.race([p5, p6]).then( + function (value) { + // Not called + }, + function (reason) { + console.log(reason); // "six" + // p6 is faster, so it rejects + } +); ``` ## 規範 diff --git a/files/zh-tw/web/javascript/reference/global_objects/promise/reject/index.md b/files/zh-tw/web/javascript/reference/global_objects/promise/reject/index.md index 65d9bd82df848d..898d3931f85422 100644 --- a/files/zh-tw/web/javascript/reference/global_objects/promise/reject/index.md +++ b/files/zh-tw/web/javascript/reference/global_objects/promise/reject/index.md @@ -9,7 +9,7 @@ slug: Web/JavaScript/Reference/Global_Objects/Promise/reject ## 語法 -```plain +```js Promise.reject(reason); ``` @@ -31,22 +31,25 @@ Promise.reject(reason); ### 使用靜態方法 Promise.reject() ```js -Promise.reject(new Error('fail')).then(function(error) { - // not called -}, function(error) { - console.log(error); // Stacktrace -}); +Promise.reject(new Error("fail")).then( + function (error) { + // not called + }, + function (error) { + console.log(error); // Stacktrace + } +); ``` -## Specifications +## 規範 {{Specifications}} -## Browser compatibility +## 瀏覽器相容性 {{Compat}} -## See also +## 參見 - {{jsxref("Promise")}} - [Selective error catching using the BlueBird Promise library](https://github.com/petkaantonov/bluebird#error-handling) diff --git a/files/zh-tw/web/javascript/reference/global_objects/promise/resolve/index.md b/files/zh-tw/web/javascript/reference/global_objects/promise/resolve/index.md index d1a2bba8be3c63..7c0503b2df376d 100644 --- a/files/zh-tw/web/javascript/reference/global_objects/promise/resolve/index.md +++ b/files/zh-tw/web/javascript/reference/global_objects/promise/resolve/index.md @@ -5,7 +5,7 @@ slug: 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)`** 方法回傳一個以 value 判定結果的 {{jsxref("Promise")}} 物件。若 value 是個 thenable(例如,具有 `then()` 方法,則回傳的 promise 將依其結果採取其最終狀態;若 value 是 promise,則作為呼叫 Promise.resolve 之結果;其他情形都將回傳以 value 實現的 promise。 ## 語法 @@ -33,18 +33,21 @@ Promise.resolve(thenable); ### 使用 `Promise.resolve` 靜態方法 ```js -Promise.resolve('Success').then(function(value) { - console.log(value); // "Success" -}, function(value) { - // not called -}); +Promise.resolve("Success").then( + function (value) { + console.log(value); // "Success" + }, + function (value) { + // not called + } +); ``` ### 判定陣列 ```js -var p = Promise.resolve([1,2,3]); -p.then(function(v) { +var p = Promise.resolve([1, 2, 3]); +p.then(function (v) { console.log(v[0]); // 1 }); ``` @@ -54,60 +57,75 @@ p.then(function(v) { ```js var original = Promise.resolve(33); var cast = Promise.resolve(original); -cast.then(function(value) { - console.log('value: ' + value); +cast.then(function (value) { + console.log("value: " + value); }); -console.log('original === cast ? ' + (original === cast)); +console.log("original === cast ? " + (original === cast)); // logs, in order: // original === cast ? true // value: 33 ``` -由於 handlers 是非同步地被調用而導致相反的紀錄順序。經由[這篇文章](/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Promise/then#回傳值)了解 then 如何運作。 +由於 handler 是非同步地被調用而導致相反的紀錄順序。經由[這篇文章](/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Promise/then#回傳值)了解 then 如何運作。 -### 判定 thenables 及拋出 Errors +### 判定 thenable 及拋出 Error ```js // Resolving a thenable object var p1 = Promise.resolve({ - then: function(onFulfill, onReject) { onFulfill('fulfilled!'); } + then: function (onFulfill, onReject) { + onFulfill("fulfilled!"); + }, }); -console.log(p1 instanceof Promise) // true, object casted to a Promise +console.log(p1 instanceof Promise); // true, object casted to a Promise -p1.then(function(v) { +p1.then( + function (v) { console.log(v); // "fulfilled!" - }, function(e) { + }, + function (e) { // not called -}); + } +); // Thenable throws before callback // Promise rejects -var thenable = { then: function(resolve) { - throw new TypeError('Throwing'); - resolve('Resolving'); -}}; +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 -}); +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 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 -}); +p3.then( + function (v) { + console.log(v); // "Resolving" + }, + function (e) { + // not called + } +); ``` ## 規範 diff --git a/files/zh-tw/web/javascript/reference/global_objects/promise/then/index.md b/files/zh-tw/web/javascript/reference/global_objects/promise/then/index.md index b861d697faa665..487d2e6341f89b 100644 --- a/files/zh-tw/web/javascript/reference/global_objects/promise/then/index.md +++ b/files/zh-tw/web/javascript/reference/global_objects/promise/then/index.md @@ -11,7 +11,7 @@ slug: Web/JavaScript/Reference/Global_Objects/Promise/then ## 語法 -```plain +```js p.then(onFulfilled[, onRejected]); p.then(function(value) { @@ -30,7 +30,7 @@ p.then(function(value) { ### 回傳值 -一個進入**擱置(pending)**狀態的 {{jsxref("Promise")}}。(只要堆疊一空)handler 函式**非同步地(asynchronously)**被呼叫。在調用 handler 後,若 handler 函式: +一個進入**擱置**(pending)狀態的 {{jsxref("Promise")}}。(只要堆疊一空)handler 函式**非同步地**(asynchronously)被呼叫。在調用 handler 後,若 handler 函式: - 回傳一個值,則 `then` 回傳之 promise 以此值被實現(resolved)。 - 拋出一個例外,則 `then` 回傳之 promise 以此例外被否決(rejected)。 @@ -44,19 +44,18 @@ p.then(function(value) { // 使用一個已實現的 promise,'then' 區塊將立即被觸發,但是它的 handlers 將是非同步地被觸發,如同 console.logs 所示 var resolvedProm = Promise.resolve(33); -var thenProm = resolvedProm.then(function(value){ - console.log("我在 main stack 之後被呼叫。收到及將回傳的值為:" + value); - return value; +var thenProm = resolvedProm.then(function (value) { + console.log("我在 main stack 之後被呼叫。收到及將回傳的值為:" + value); + return value; }); // 立即紀錄 thenProm console.log(thenProm); // 我們可以使用 setTimeout 以延遲(postpone)函式執行直到堆疊為空 -setTimeout(function(){ - console.log(thenProm); +setTimeout(function () { + console.log(thenProm); }); - // 紀錄結果,依序為: // Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined} // "我在 main stack 之後被呼叫。收到及將回傳的值為:33" @@ -72,17 +71,20 @@ setTimeout(function(){ ### 運用 `then` 方法 ```js -var p1 = new Promise( (resolve, reject) => { - resolve('Success!'); +var p1 = new Promise((resolve, reject) => { + resolve("Success!"); // or // reject ("Error!"); -} ); +}); -p1.then( value => { - console.log(value); // Success! -}, reason => { - console.log(reason); // Error! -} ); +p1.then( + (value) => { + console.log(value); // Success! + }, + (reason) => { + console.log(reason); // Error! + } +); ``` ### 串接 @@ -92,12 +94,12 @@ p1.then( value => { 如果傳入 `then` 的 handler 函式回傳一個 promise,一個等價的 `Promise` 將被展現給方法串接中的下一個 then 。以下程式碼片段透過 `setTimout` 函式模擬非同步程式碼。 ```js -Promise.resolve('foo') +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'; + .then(function (string) { + return new Promise(function (resolve, reject) { + setTimeout(function () { + string += "bar"; resolve(string); }, 1); }); @@ -105,20 +107,22 @@ Promise.resolve('foo') // 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'; + .then(function (string) { + setTimeout(function () { + string += "baz"; console.log(string); - }, 1) + }, 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"); + .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 @@ -129,18 +133,18 @@ Promise.resolve('foo') 當 handler 僅回傳一個值,實際上它將回傳 `Promise.resolve()`. ```js -var p2 = new Promise(function(resolve, reject) { +var p2 = new Promise(function (resolve, reject) { resolve(1); }); -p2.then(function(value) { +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 +}).then(function (value) { + console.log(value + "- This synchronous usage is virtually pointless"); // 2- This synchronous usage is virtually pointless }); -p2.then(function(value) { +p2.then(function (value) { console.log(value); // 1 }); ``` @@ -149,38 +153,44 @@ p2.then(function(value) { ```js Promise.resolve() - .then( () => { + .then(() => { // 使 .then() 回傳一個被否決的 Promise - throw 'Oh no!'; + throw "Oh no!"; }) - .then( () => { - console.log( 'Not called.' ); - }, reason => { - console.error( 'onRejected function called: ', reason ); - }); + .then( + () => { + console.log("Not called."); + }, + (reason) => { + console.error("onRejected function called: ", reason); + } + ); ``` 在所有其他情形,實現中的 Promise 被回傳。在以下例子中,第一個 `then()` 將回傳一個實現中包裹 42 的 promise,即使串接中的前一個 Promise 被否決。 ```js Promise.reject() - .then( () => 99, () => 42 ) // onRejected returns 42 which is wrapped in a resolving Promise - .then( solution => console.log( 'Resolved with ' + solution ) ); // Resolved with 42 + .then( + () => 99, + () => 42 + ) // onRejected returns 42 which is wrapped in a resolving Promise + .then((solution) => console.log("Resolved with " + solution)); // Resolved with 42 ``` 實務上,使用 `catch` 捕捉被否決的 promise 較理想的,而不建議使用兩個引數 `then` 語法,如下展示。 ```js Promise.resolve() - .then( () => { + .then(() => { // Makes .then() return a rejected promise - throw 'Oh no!'; + throw "Oh no!"; }) - .catch( reason => { - console.error( 'onRejected function called: ', reason ); + .catch((reason) => { + console.error("onRejected function called: ", reason); }) - .then( () => { - console.log( "I am always called even if the prior then's promise rejects" ); + .then(() => { + console.log("I am always called even if the prior then's promise rejects"); }); ``` @@ -192,14 +202,14 @@ function fetch_current_data() { // 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') { + 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() + // fetch_current_data().then() }); } ``` @@ -218,28 +228,34 @@ function rejectLater(resolve, reject) { }, 1000); } -var p1 = Promise.resolve('foo'); -var p2 = p1.then(function() { +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() { +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 -}); +p3.then( + function (v) { + // not called + console.log("resolved", v); + }, + function (e) { + console.log("rejected", e); // "rejected", 20 + } +); ``` ## 規範 diff --git a/files/zh-tw/web/javascript/reference/global_objects/proxy/index.md b/files/zh-tw/web/javascript/reference/global_objects/proxy/index.md index 7688c5750e503e..ed323e384471c8 100644 --- a/files/zh-tw/web/javascript/reference/global_objects/proxy/index.md +++ b/files/zh-tw/web/javascript/reference/global_objects/proxy/index.md @@ -18,7 +18,7 @@ slug: Web/JavaScript/Reference/Global_Objects/Proxy ## 語法 -```plain +```js var p = new Proxy(target, handler); ``` @@ -42,11 +42,9 @@ In this simple example the number `37` gets returned as the default value when t ```js var handler = { - get: function(target, name) { - return name in target ? - target[name] : - 37; - } + get: function (target, name) { + return name in target ? target[name] : 37; + }, }; var p = new Proxy({}, handler); @@ -54,7 +52,7 @@ p.a = 1; p.b = undefined; console.log(p.a, p.b); // 1, undefined -console.log('c' in p, p.c); // false, 37 +console.log("c" in p, p.c); // false, 37 ``` ### No-op forwarding proxy @@ -76,13 +74,13 @@ With a `Proxy`, you can easily validate the passed value for an object. This exa ```js let validator = { - set: function(obj, prop, value) { - if (prop === 'age') { + set: function (obj, prop, value) { + if (prop === "age") { if (!Number.isInteger(value)) { - throw new TypeError('The age is not an integer'); + throw new TypeError("The age is not an integer"); } if (value > 200) { - throw new RangeError('The age seems invalid'); + throw new RangeError("The age seems invalid"); } } @@ -91,14 +89,14 @@ let validator = { // 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 = "young"; // Throws an exception person.age = 300; // Throws an exception ``` @@ -109,40 +107,41 @@ A function proxy could easily extend a constructor with a new constructor. This ```js function extend(sup, base) { var descriptor = Object.getOwnPropertyDescriptor( - base.prototype, 'constructor' + base.prototype, + "constructor" ); base.prototype = Object.create(sup.prototype); var handler = { - construct: function(target, args) { + construct: function (target, args) { var obj = Object.create(base.prototype); this.apply(target, obj, args); return obj; }, - apply: function(target, that, args) { + 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); + Object.defineProperty(base.prototype, "constructor", descriptor); return proxy; } -var Person = function(name) { +var Person = function (name) { this.name = name; }; -var Boy = extend(Person, function(name, age) { +var Boy = extend(Person, function (name, age) { this.age = age; }); -Boy.prototype.sex = 'M'; +Boy.prototype.sex = "M"; -var Peter = new Boy('Peter', 13); -console.log(Peter.sex); // "M" +var Peter = new Boy("Peter", 13); +console.log(Peter.sex); // "M" console.log(Peter.name); // "Peter" -console.log(Peter.age); // 13 +console.log(Peter.age); // 13 ``` ### Manipulating DOM nodes @@ -150,36 +149,38 @@ console.log(Peter.age); // 13 Sometimes you want to toggle the attribute or class name of two different elements. Here's how using the [`set`](/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/set) handler. ```js -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'); +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; + // The default behavior to store the value + obj[prop] = newval; - // Indicate success - return true; + // Indicate success + return true; + }, } -}); +); -let i1 = view.selected = document.getElementById('item-1'); -console.log(i1.getAttribute('aria-selected')); // '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' +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 @@ -187,44 +188,46 @@ console.log(i2.getAttribute('aria-selected')); // 'true' 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. ```js -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]; +let products = new Proxy( + { + browsers: ["Internet Explorer", "Netscape"], }, - set: function(obj, prop, value) { - // An extra property - if (prop === 'latestBrowser') { - obj.browsers.push(value); - return true; - } + { + get: function (obj, prop) { + // An extra property + if (prop === "latestBrowser") { + return obj.browsers[obj.browsers.length - 1]; + } - // Convert the value if it is not an array - if (typeof value === 'string') { - value = [value]; - } + // 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; + } - // The default behavior to store the value - obj[prop] = value; + // Convert the value if it is not an array + if (typeof value === "string") { + value = [value]; + } - // Indicate success - return true; + // 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) +products.browsers = "Firefox"; // pass a string (by mistake) console.log(products.browsers); // ['Firefox'] <- no problem, the value is an array -products.latestBrowser = 'Chrome'; +products.latestBrowser = "Chrome"; console.log(products.browsers); // ['Firefox', 'Chrome'] console.log(products.latestBrowser); // 'Chrome' ``` @@ -234,58 +237,61 @@ console.log(products.latestBrowser); // 'Chrome' This proxy extends an array with some utility features. As you see, you can flexibly "define" properties without using [`Object.defineProperties`](/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperties). This example can be adapted to find a table row by its cell. In that case, the target will be [`table.rows`](/zh-TW/docs/DOM/table.rows). ```js -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 = {}; +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]; + } - for (let product of obj) { - if (product.name === prop) { - result = product; + // Get the number of products; an alias of products.length + if (prop === "number") { + return obj.length; } - if (types[product.type]) { - types[product.type].push(product); - } else { - types[product.type] = [product]; + + 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 a product by name + if (result) { + return result; + } - // Get products by type - if (prop in types) { - return types[prop]; - } + // Get products by type + if (prop in types) { + return types[prop]; + } - // Get product types - if (prop === 'types') { - return Object.keys(types); - } + // Get product types + if (prop === "types") { + return Object.keys(types); + } - return undefined; + 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["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 @@ -306,11 +312,15 @@ var docCookies = new Proxy(docCookies, { return oTarget[sKey] || oTarget.getItem(sKey) || undefined; }, set: function (oTarget, sKey, vValue) { - if (sKey in oTarget) { return false; } + if (sKey in oTarget) { + return false; + } return oTarget.setItem(sKey, vValue); }, deleteProperty: function (oTarget, sKey) { - if (sKey in oTarget) { return false; } + if (sKey in oTarget) { + return false; + } return oTarget.removeItem(sKey); }, enumerate: function (oTarget, sKey) { @@ -323,26 +333,30 @@ var docCookies = new Proxy(docCookies, { return sKey in oTarget || oTarget.hasItem(sKey); }, defineProperty: function (oTarget, sKey, oDesc) { - if (oDesc && 'value' in oDesc) { oTarget.setItem(sKey, oDesc.value); } + 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; + 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')); +console.log((docCookies.my_cookie1 = "First value")); +console.log(docCookies.getItem("my_cookie1")); -docCookies.setItem('my_cookie1', 'Changed value'); +docCookies.setItem("my_cookie1", "Changed value"); console.log(docCookies.my_cookie1); ``` diff --git a/files/zh-tw/web/javascript/reference/global_objects/rangeerror/index.md b/files/zh-tw/web/javascript/reference/global_objects/rangeerror/index.md index cdadc106a5d725..7fe6bb72de72d5 100644 --- a/files/zh-tw/web/javascript/reference/global_objects/rangeerror/index.md +++ b/files/zh-tw/web/javascript/reference/global_objects/rangeerror/index.md @@ -9,7 +9,7 @@ slug: Web/JavaScript/Reference/Global_Objects/RangeError ## 語法 -```plain +```js-nolint new RangeError([message[, fileName[, lineNumber]]]) ``` @@ -56,51 +56,41 @@ new RangeError([message[, fileName[, lineNumber]]]) ## 範例 -### 使用 `RangeError` (數值) +### 使用 `RangeError`(數值) ```js -function check(n) -{ - if(!(n >= -500 && n <= 500)) - { - throw new RangeError("The argument must be between -500 and 500."); - } +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. - } +try { + check(2000); +} catch (error) { + if (error instanceof RangeError) { + // Handle the error. + } } ``` -### 使用 `RangeError` (非數值) +### 使用 `RangeError`(非數值) ```js -function check(value) -{ - if(["apple", "banana", "carrot"].includes(value) === false) - { - throw new RangeError("The argument must be an \"apple\", \"banana\", or \"carrot\"."); - } +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. - } +try { + check("cabbage"); +} catch (error) { + if (error instanceof RangeError) { + // Handle the error. + } } ``` @@ -112,7 +102,7 @@ catch(error) {{Compat}} -## 另見 +## 參見 - {{jsxref("Error")}} - {{jsxref("RangeError.prototype")}} diff --git a/files/zh-tw/web/javascript/reference/global_objects/regexp/index.md b/files/zh-tw/web/javascript/reference/global_objects/regexp/index.md index d48d955f55a16f..bffe6bbd96d8d6 100644 --- a/files/zh-tw/web/javascript/reference/global_objects/regexp/index.md +++ b/files/zh-tw/web/javascript/reference/global_objects/regexp/index.md @@ -11,17 +11,17 @@ slug: Web/JavaScript/Reference/Global_Objects/RegExp ## 說明 -建立 `RegExp` 物件有兩種方式:_文字表示法 (literal notation)_ 和 _建構子 (constructor)。_ +建立 `RegExp` 物件有兩種方式:_文字表示法_(literal notation)和*建構子*(constructor)。 -- **文字表示法** 的參數,頭尾以斜線標註,且不使用引號標註。 -- **建構子函式** 的參數,頭尾不以斜線標註,但使用引號標註。 +- **文字表示法**的參數,頭尾以斜線標註,且不使用引號標註。 +- **建構子函式**的參數,頭尾不以斜線標註,但使用引號標註。 以下的表達式會建立出相同的正規表達式: ```js -/ab+c/i -new RegExp(/ab+c/, 'i') // literal notation -new RegExp('ab+c', 'i') // 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. @@ -35,8 +35,8 @@ When using the constructor function, the normal string escape rules (preceding s For example, the following are equivalent: ```js -let re = /\w+/ -let re = new RegExp('\\w+') +let re = /\w+/; +let re = new RegExp("\\w+"); ``` ## Constructor @@ -118,10 +118,10 @@ The following script uses the {{jsxref("String.prototype.replace()", "replace()" In the replacement text, the script uses `$1` and `$2` to indicate the results of the corresponding matching parentheses in the regular expression pattern. ```js -let re = /(\w+)\s(\w+)/ -let str = 'John Smith' -let newstr = str.replace(re, '$2, $1') -console.log(newstr) +let re = /(\w+)\s(\w+)/; +let str = "John Smith"; +let newstr = str.replace(re, "$2, $1"); +console.log(newstr); ``` This displays `"Smith, John"`. @@ -131,9 +131,9 @@ This displays `"Smith, John"`. The default line ending varies depending on the platform (Unix, Windows, etc.). The line splitting provided in this example works on all platforms. ```js -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' ] +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. @@ -141,7 +141,7 @@ Note that the order of the patterns in the regular expression matters. ### Using regular expression on multiple lines ```js -let s = 'Please yes\nmake my day!' +let s = "Please yes\nmake my day!"; s.match(/yes.*day/); // Returns null @@ -155,14 +155,14 @@ s.match(/yes[^]*day/); The [sticky flag](/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/RegExp/sticky) indicates that the regular expression performs sticky matching in the target string by attempting to match starting at {{jsxref("RegExp.prototype.lastIndex")}}. ```js -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) +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 @@ -171,7 +171,8 @@ With the sticky flag y, the next match has to happen at the lastIndex position, ```js re = /\d/y; -while (r = re.exec("123 456")) console.log(r, "AND re.lastIndex", re.lastIndex); +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 @@ -190,16 +191,16 @@ To match characters from other languages such as Cyrillic or Hebrew, use `\uhhhh This example demonstrates how one can separate out Unicode characters from a word. ```js -let text = 'Образец text на русском языке' -let regex = /[\u0400-\u04FF]+/g +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 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' +let match2 = regex.exec(text); +console.log(match2[0]); // logs 'на' [did not log 'text'] +console.log(regex.lastIndex); // logs '15' // and so on ``` @@ -209,8 +210,8 @@ The [Unicode property escapes](/zh-TW/docs/Web/JavaScript/Guide/Regular_Expressi ### Extracting sub-domain name from URL ```js -let url = 'http://xxx.domain.com' -console.log(/[^.]+/.exec(url)[0].substr(7)) // logs 'xxx' +let url = "http://xxx.domain.com"; +console.log(/[^.]+/.exec(url)[0].substr(7)); // logs 'xxx' ``` ## Specifications @@ -227,13 +228,13 @@ Starting with Firefox 34, in the case of a capturing group with quantifiers prev ```js // Firefox 33 or older -'x'.replace(/x(.)?/g, function(m, group) { +"x".replace(/x(.)?/g, function (m, group) { console.log("'group:" + group + "'"); }); // 'group:' // Firefox 34 or newer -'x'.replace(/x(.)?/g, function(m, group) { +"x".replace(/x(.)?/g, function (m, group) { console.log("'group:" + group + "'"); }); // 'group:undefined' diff --git a/files/zh-tw/web/javascript/reference/global_objects/set/add/index.md b/files/zh-tw/web/javascript/reference/global_objects/set/add/index.md index 5c7e2e87bc259e..0cb1fda346c491 100644 --- a/files/zh-tw/web/javascript/reference/global_objects/set/add/index.md +++ b/files/zh-tw/web/javascript/reference/global_objects/set/add/index.md @@ -11,7 +11,7 @@ slug: Web/JavaScript/Reference/Global_Objects/Set/add ## 語法 -```plain +```js mySet.add(value); ``` @@ -32,7 +32,7 @@ mySet.add(value); var mySet = new Set(); mySet.add(1); -mySet.add(5).add('some text'); // chainable +mySet.add(5).add("some text"); // chainable console.log(mySet); // Set [1, 5, "some text"] @@ -46,7 +46,7 @@ console.log(mySet); {{Compat}} -## 另見 +## 參見 - {{jsxref("Set")}} - {{jsxref("Set.prototype.delete()")}} diff --git a/files/zh-tw/web/javascript/reference/global_objects/set/clear/index.md b/files/zh-tw/web/javascript/reference/global_objects/set/clear/index.md index 85f2e0d275d670..75e9bc9fca453c 100644 --- a/files/zh-tw/web/javascript/reference/global_objects/set/clear/index.md +++ b/files/zh-tw/web/javascript/reference/global_objects/set/clear/index.md @@ -11,13 +11,13 @@ slug: Web/JavaScript/Reference/Global_Objects/Set/clear ## 語法 -```plain +```js mySet.clear(); ``` ### 回傳值 -{{jsxref("undefined")}}. +{{jsxref("undefined")}}。 ## 範例 @@ -26,15 +26,15 @@ mySet.clear(); ```js var mySet = new Set(); mySet.add(1); -mySet.add('foo'); +mySet.add("foo"); -mySet.size; // 2 -mySet.has('foo'); // true +mySet.size; // 2 +mySet.has("foo"); // true mySet.clear(); -mySet.size; // 0 -mySet.has('bar') // false +mySet.size; // 0 +mySet.has("bar"); // false ``` ## 規範 @@ -45,7 +45,7 @@ mySet.has('bar') // false {{Compat}} -## 另見 +## 參見 - {{jsxref("Set")}} - {{jsxref("Set.prototype.delete()")}} diff --git a/files/zh-tw/web/javascript/reference/global_objects/set/delete/index.md b/files/zh-tw/web/javascript/reference/global_objects/set/delete/index.md index ff9ac01220b4c1..8d633c0b7e716d 100644 --- a/files/zh-tw/web/javascript/reference/global_objects/set/delete/index.md +++ b/files/zh-tw/web/javascript/reference/global_objects/set/delete/index.md @@ -11,7 +11,7 @@ slug: Web/JavaScript/Reference/Global_Objects/Set/delete ## 語法 -```plain +```js mySet.delete(value); ``` @@ -30,12 +30,12 @@ mySet.delete(value); ```js var mySet = new Set(); -mySet.add('foo'); +mySet.add("foo"); -mySet.delete('bar'); // Returns false. No "bar" element found to be deleted. -mySet.delete('foo'); // Returns true. Successfully removed. +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. +mySet.has("foo"); // Returns false. The "foo" element is no longer present. ``` 下方展示了如何從一個 Set 中移除物件。 @@ -43,16 +43,16 @@ mySet.has('foo'); // Returns false. The "foo" element is no longer present. ```js var setObj = new Set(); // Create a New Set. -setObj.add({x: 10, y: 20}); // Add object in the set. +setObj.add({ x: 10, y: 20 }); // Add object in the set. -setObj.add({x: 20, y: 30}); // 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) +setObj.forEach(function (point) { + if (point.x > 10) { + setObj.delete(point); } -}) +}); ``` ## 規範 @@ -63,7 +63,7 @@ setObj.forEach(function(point){ {{Compat}} -## 另見 +## 參見 - {{jsxref("Set")}} - {{jsxref("Set.prototype.clear()")}} diff --git a/files/zh-tw/web/javascript/reference/global_objects/set/entries/index.md b/files/zh-tw/web/javascript/reference/global_objects/set/entries/index.md index ff7d60fc10c8a3..3c81e72250e27b 100644 --- a/files/zh-tw/web/javascript/reference/global_objects/set/entries/index.md +++ b/files/zh-tw/web/javascript/reference/global_objects/set/entries/index.md @@ -3,17 +3,21 @@ title: Set.prototype.entries() slug: Web/JavaScript/Reference/Global_Objects/Set/entries --- -{{JSRef}}**`entries()`** 方法回傳一個 `Iterator` 物件,其包含著一個由插入順序排序,`Set` 物件中每個元素的** `[value, value]`** 陣列。儘管對 `Set` 物件來說沒有像 `Map` 一樣的 `key` 概念,為了確保這個 API 運作的與 `Map` 相似,每個 _entry_ 都有同樣的值同時作為其 _key_ 和 _value_ ,因此回傳的是一個**`[value, value]`** 的陣列。{{EmbedInteractiveExample("pages/js/set-prototype-entries.html")}} +{{JSRef}} + +**`entries()`** 方法回傳一個 `Iterator` 物件,其包含著一個由插入順序排序,`Set` 物件中每個元素的 **`[value, value]`** 陣列。儘管對 `Set` 物件來說沒有像 `Map` 一樣的 `key` 概念,為了確保這個 API 運作的與 `Map` 相似,每個 _entry_ 都有同樣的值同時作為其 _key_ 和 _value_ ,因此回傳的是一個 **`[value, value]`** 的陣列。 + +{{EmbedInteractiveExample("pages/js/set-prototype-entries.html")}} ## 語法 -```plain +```js-nolint mySet.entries() ``` ### 回傳值 -一個新的 `Iterator` 物件,包含著一個由插入順序排序,`Set` 物件中每個元素的** `[value, value]`** 陣列。 +一個新的 `Iterator` 物件,包含著一個由插入順序排序,`Set` 物件中每個元素的 **`[value, value]`** 陣列。 ## 範例 @@ -21,9 +25,9 @@ mySet.entries() ```js var mySet = new Set(); -mySet.add('foobar'); +mySet.add("foobar"); mySet.add(1); -mySet.add('baz'); +mySet.add("baz"); var setIter = mySet.entries(); @@ -40,7 +44,7 @@ console.log(setIter.next().value); // ["baz", "baz"] {{Compat}} -## 另見 +## 參見 - {{jsxref("Set.prototype.keys()")}} - {{jsxref("Set.prototype.values()")}} diff --git a/files/zh-tw/web/javascript/reference/global_objects/set/has/index.md b/files/zh-tw/web/javascript/reference/global_objects/set/has/index.md index 5a03692e4c7de1..fba5d1c87eaa2c 100644 --- a/files/zh-tw/web/javascript/reference/global_objects/set/has/index.md +++ b/files/zh-tw/web/javascript/reference/global_objects/set/has/index.md @@ -11,7 +11,7 @@ slug: Web/JavaScript/Reference/Global_Objects/Set/has ## 語法 -```plain +```js mySet.has(value); ``` @@ -22,7 +22,7 @@ mySet.has(value); ### 回傳值 -回傳 `true` 如果給定值存在在 `Set` 物件中;反之回傳 `false` 。 +回傳 `true` 如果給定值存在在 `Set` 物件中;反之回傳 `false`。 > **備註:** 技術上來說,`has()` 使用了 [`sameValueZero`](/zh-TW/docs/Web/JavaScript/Equality_comparisons_and_sameness#Same-value-zero_equality) 算法來判斷給定元素的存在與否。 @@ -32,18 +32,18 @@ mySet.has(value); ```js var mySet = new Set(); -mySet.add('foo'); +mySet.add("foo"); -mySet.has('foo'); // returns true -mySet.has('bar'); // returns false +mySet.has("foo"); // returns true +mySet.has("bar"); // returns false var set1 = new Set(); -var obj1 = {'key1': 1}; +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 +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 ``` ## 規範 @@ -54,7 +54,7 @@ set1.add({'key1': 1}); // now set1 contains 2 entries {{Compat}} -## 另見 +## 參見 - {{jsxref("Set")}} - {{jsxref("Set.prototype.add()")}} diff --git a/files/zh-tw/web/javascript/reference/global_objects/set/index.md b/files/zh-tw/web/javascript/reference/global_objects/set/index.md index 0ac9eef9c665a9..a19f6eb57eeb09 100644 --- a/files/zh-tw/web/javascript/reference/global_objects/set/index.md +++ b/files/zh-tw/web/javascript/reference/global_objects/set/index.md @@ -11,7 +11,7 @@ slug: Web/JavaScript/Reference/Global_Objects/Set ## 語法 -```plain +```js new Set([iterable]); ``` @@ -87,26 +87,26 @@ 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("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.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(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.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} ] +console.log(mySet); // Set [ 1, "some text", Object {a: 1, b: 2}, Object {a: 1, b: 2} ] ``` ### 迭代 Sets @@ -131,7 +131,7 @@ var myArr = Array.from(mySet); // [1, "some text", {"a": 1, "b": 2}, {"a": 1, "b // the following will also work if run in an HTML document mySet.add(document.body); -mySet.has(document.querySelector('body')); // true +mySet.has(document.querySelector("body")); // true // converting between Set and Array mySet2 = new Set([1, 2, 3, 4]); @@ -139,13 +139,13 @@ mySet2.size; // 4 [...mySet2]; // [1, 2, 3, 4] // intersect can be simulated via -var intersection = new Set([...set1].filter(x => set2.has(x))); +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))); +var difference = new Set([...set1].filter((x) => !set2.has(x))); // Iterate set entries with forEach -mySet.forEach(function(value) { +mySet.forEach(function (value) { console.log(value); }); @@ -158,45 +158,45 @@ mySet.forEach(function(value) { ### 實作基本的 set 操作 ```js -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); +Set.prototype.isSuperset = function (subset) { + for (var elem of subset) { + if (!this.has(elem)) { + return false; } - return union; -} - -Set.prototype.intersection = function(setB) { - var intersection = new Set(); - for (var elem of setB) { - if (this.has(elem)) { - intersection.add(elem); - } + } + 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; -} + } + 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]); + 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] @@ -207,12 +207,12 @@ setA.difference(setC); // => Set [1, 2] ### 與 `Array` 物件關聯 ```js -var myArray = ['value1', 'value2', 'value3']; +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 +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 @@ -221,10 +221,10 @@ console.log([...mySet]); // Will show you exactly the same Array as myArray ### 與 `Strings` 關聯 ```js -var text = 'India'; +var text = "India"; -var mySet = new Set(text); // Set ['I', 'n', 'd', 'i', 'a'] -mySet.size; // 5 +var mySet = new Set(text); // Set ['I', 'n', 'd', 'i', 'a'] +mySet.size; // 5 ``` ## 規範 diff --git a/files/zh-tw/web/javascript/reference/global_objects/set/values/index.md b/files/zh-tw/web/javascript/reference/global_objects/set/values/index.md index 563f310569ef9e..f0b7c09bcbc68d 100644 --- a/files/zh-tw/web/javascript/reference/global_objects/set/values/index.md +++ b/files/zh-tw/web/javascript/reference/global_objects/set/values/index.md @@ -7,13 +7,13 @@ slug: Web/JavaScript/Reference/Global_Objects/Set/values **`values()`** 方法回傳一個 `Iterator` 物件,包含著 `Set` 物件中所有元素,由插入順序排序。 -**`keys()`** 是這個方法的替身 (為了與 {{jsxref("Map")}} 物件保持相似性);他運行的完全一模一樣,回傳 `Set` 中元素的 **values** 。 +**`keys()`** 是這個方法的替身(為了與 {{jsxref("Map")}} 物件保持相似性);他運行的完全一模一樣,回傳 `Set` 中元素的 **values**。 {{EmbedInteractiveExample("pages/js/set-prototype-values.html")}} ## 語法 -```plain +```js mySet.values(); ``` @@ -27,9 +27,9 @@ mySet.values(); ```js var mySet = new Set(); -mySet.add('foo'); -mySet.add('bar'); -mySet.add('baz'); +mySet.add("foo"); +mySet.add("bar"); +mySet.add("baz"); var setIter = mySet.values(); @@ -46,6 +46,6 @@ console.log(setIter.next().value); // "baz" {{Compat}} -## 另見 +## 參見 - {{jsxref("Set.prototype.entries()")}} diff --git a/files/zh-tw/web/javascript/reference/global_objects/string/concat/index.md b/files/zh-tw/web/javascript/reference/global_objects/string/concat/index.md index ace7ef59165d42..b86fb6c46fbef3 100644 --- a/files/zh-tw/web/javascript/reference/global_objects/string/concat/index.md +++ b/files/zh-tw/web/javascript/reference/global_objects/string/concat/index.md @@ -11,7 +11,7 @@ slug: Web/JavaScript/Reference/Global_Objects/String/concat ## 語法 -```js +```js-nolint concat(str1) concat(str1, str2) concat(str1, str2, ... , strN) @@ -45,21 +45,21 @@ concat(str1, str2, ... , strN) 以下的例子示範如何將那些給定的字串組合成新的字串。 ```js -let hello = 'Hello, ' -console.log(hello.concat('Kevin', '. Have a nice day.')) +let hello = "Hello, "; +console.log(hello.concat("Kevin", ". Have a nice day.")); // Hello, Kevin. Have a nice day. -let greetList = ['Hello', ' ', 'Venkat', '!'] -"".concat(...greetList) // "Hello Venkat!" +let greetList = ["Hello", " ", "Venkat", "!"]; +"".concat(...greetList); // "Hello Venkat!" -"".concat({}) // [object Object] -"".concat([]) // "" -"".concat(null) // "null" -"".concat(true) // "true" -"".concat(4, 5) // "45" +"".concat({}); // [object Object] +"".concat([]); // "" +"".concat(null); // "null" +"".concat(true); // "true" +"".concat(4, 5); // "45" ``` -## 規格 +## 規範 {{Specifications}} diff --git a/files/zh-tw/web/javascript/reference/global_objects/string/index.md b/files/zh-tw/web/javascript/reference/global_objects/string/index.md index 7fc6b9889b0ee5..90da4e3aea94bb 100644 --- a/files/zh-tw/web/javascript/reference/global_objects/string/index.md +++ b/files/zh-tw/web/javascript/reference/global_objects/string/index.md @@ -38,21 +38,21 @@ String(thing) 除了常規的、可印出來的字元,特殊字元也可以被跳脫符號來表示編碼。 -| 代碼 | 輸出 | -| ------------------------ | --------------------------------------------- | -| `\0` | 空字元 | -| `\'` | 單引號 | -| `\"` | 雙引號 | -| `\\` | 反斜線 | -| `\n` | 斷行 | -| `\r` | 回車 | -| `\v` | 垂直制表 | -| `\t` | 制表 | -| `\b` | 退格 | -| `\f` | 饋頁 | -| `\uXXXX` | unicode 代碼 | +| 代碼 | 輸出 | +| ------------------------ | ------------------------------------ | +| `\0` | 空字元 | +| `\'` | 單引號 | +| `\"` | 雙引號 | +| `\\` | 反斜線 | +| `\n` | 斷行 | +| `\r` | 回車 | +| `\v` | 垂直制表 | +| `\t` | 制表 | +| `\b` | 退格 | +| `\f` | 饋頁 | +| `\uXXXX` | unicode 代碼 | | `\u{X}` ... `\u{XXXXXX}` | unicode 代碼 {{experimental_inline}} | -| `\xXX` | Latin-1 字元 | +| `\xXX` | Latin-1 字元 | > **備註:** 和其他語言不同,JavaScript 將單引號字串和雙引號字串是做相同;因此,上述的序列可以在單引號或雙引號中作用。 @@ -63,15 +63,17 @@ String(thing) 你可以用 [+](/zh-TW/docs/Web/JavaScript/Guide/Expressions_and_operators#字串運算子) 運算子附加多個字串在一起,像是這樣: ```js -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."; ``` -或者,你可以在每一行尾端用反斜線字元("\\")表示字串會繼續被顯示在下一列。 你必須要確定在反斜線後面沒有任何空白或其他字元,甚至是縮排;否則這個方法將失效。 這個形式看起來像這樣: +或者,你可以在每一行尾端用反斜線字元("\\")表示字串會繼續被顯示在下一列。 你必須要確定在反斜線後面沒有任何空白或其他字元,甚至是縮排;否則這個方法將失效。 這個形式看起來像這樣: -```plain -let longString = "This is a very long string which needs \ +```js +let longString = + "This is a very long string which needs \ to wrap across multiple lines because \ otherwise my code is unreadable."; ``` @@ -87,13 +89,13 @@ otherwise my code is unreadable."; 有兩個方法可以存取字串中個別的字元。第一個是用 {{jsxref("String.charAt", "charAt")}} 方法: ```js -return 'cat'.charAt(1); // 回傳 "a" +return "cat".charAt(1); // 回傳 "a" ``` 另一個(在 ECMAScript 5 中被提到)方法是將字串當作一個類似陣列的物件,直接存取字串中對應的數值索引。 ```js -return 'cat'[1]; // 回傳 "a" +return "cat"[1]; // 回傳 "a" ``` 對於存取字元使用的括號表達式,沒辦法去刪除或指派一個值給這些屬性。 這些屬性既非可寫的,也非可設定的。(參見 {{jsxref("Object.defineProperty")}}) @@ -105,12 +107,11 @@ C 語言的開發者有 `strcmp()` 函式可以用來比較字串。 在 JavaScr ```js var a = "a"; var b = "b"; -if (a < b) // true +if (a < b) + // true print(a + " 小於 " + b); -else if (a > b) - print(a + " 大於 " + b); -else - print(a + " 和 " + b + " 相等"); +else if (a > b) print(a + " 大於 " + b); +else print(a + " 和 " + b + " 相等"); ``` 這樣類似的結果,也能使用繼承 `String` 實體的 {{jsxref("String.localeCompare", "localeCompare")}} 方法來實現。 @@ -126,16 +127,16 @@ var s_prim = "foo"; var s_obj = new String(s_prim); console.log(typeof s_prim); // 印出 "string" -console.log(typeof s_obj); // 印出 "object" +console.log(typeof s_obj); // 印出 "object" ``` 字串原始型別和 `String` 物件也會在使用 {{jsxref("Global_Objects/eval", "eval")}} 時給出不同的結果。 原始型別傳進 `eval` 會被視為原始代碼;`String` 物件則會回傳,且被視作是其他物件。舉個例子: ```js -s1 = "2 + 2"; // 建立一個字串原始型別 -s2 = new String("2 + 2"); // 建立一個字串物件 -console.log(eval(s1)); // 回傳數字 4 -console.log(eval(s2)); // 回傳字串 "2 + 2" +s1 = "2 + 2"; // 建立一個字串原始型別 +s2 = new String("2 + 2"); // 建立一個字串物件 +console.log(eval(s1)); // 回傳數字 4 +console.log(eval(s2)); // 回傳字串 "2 + 2" ``` 因為一些原因,程式碼也許在遇到 `String` 物件時,但需要的卻是字串原始型別;儘管如此,通常作者們不需要擔心它的差異。 @@ -166,7 +167,7 @@ The `String` instance methods are also available in Firefox as of JavaScript 1.6 ```js var num = 15; -alert(String.replace(num, /5/, '2')); +alert(String.replace(num, /5/, "2")); ``` [Generics](/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array#Array_generic_methods) are also available on {{jsxref("Global_Objects/Array", "Array")}} methods. @@ -178,32 +179,50 @@ The following is a shim to provide support to non-supporting browsers: // 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]); - } -}()); + "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 diff --git a/files/zh-tw/web/javascript/reference/global_objects/string/localecompare/index.md b/files/zh-tw/web/javascript/reference/global_objects/string/localecompare/index.md index b8adc0e7a2e14b..9c806f04039898 100644 --- a/files/zh-tw/web/javascript/reference/global_objects/string/localecompare/index.md +++ b/files/zh-tw/web/javascript/reference/global_objects/string/localecompare/index.md @@ -13,7 +13,7 @@ slug: Web/JavaScript/Reference/Global_Objects/String/localeCompare ## 語法 -```js +```js-nolint localeCompare(compareString) localeCompare(compareString, locales) localeCompare(compareString, locales, options) @@ -29,10 +29,13 @@ localeCompare(compareString, locales, options) - `compareString` - : 要和`referenceStr`進行比較的字串 - `locales` {{optional_inline}} + - : 「BCP 47 語言標籤」的字串或是陣列。相當於`Intl.Collator()`的[`locales`](/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#locales) 參數。 如果使用的環境並未實現 `Intl.Collator`,此參數會被忽略,並且視同採用當前主機的語言環境 + - `options` {{optional_inline}} + - : 一個處理輸出格式的物件。相當於`Intl.Collator()`的 [`options`](/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#options)參數。 如果使用的環境並未實現`Intl.Collator` ,此參數會被忽略。 @@ -68,11 +71,11 @@ localeCompare(compareString, locales, options) ```js // "a" 在 "c" 之前,所以會回傳負數 -'a'.localeCompare('c'); // -2、-1 或是其他負數值 +"a".localeCompare("c"); // -2、-1 或是其他負數值 // 按字母順序,“check”的順序在“against”之後,所以回傳正數 -'check'.localeCompare('against'); // 2、1 或其他正數值 +"check".localeCompare("against"); // 2、1 或其他正數值 // "a" 和 "a" 相同,所以回傳 0 -'a'.localeCompare('a'); // 0 +"a".localeCompare("a"); // 0 ``` ### 陣列排序 @@ -80,8 +83,8 @@ localeCompare(compareString, locales, options) `localeCompare()` 用來進行「不分大小寫」的排序 ```js -let items = ['réservé', 'Premier', 'Cliché', 'communiqué', 'café', 'Adieu']; -items.sort((a, b) => a.localeCompare(b, 'fr', { ignorePunctuation: true })); +let items = ["réservé", "Premier", "Cliché", "communiqué", "café", "Adieu"]; +items.sort((a, b) => a.localeCompare(b, "fr", { ignorePunctuation: true })); // ['Adieu', 'café', 'Cliché', 'communiqué', 'Premier', 'réservé'] ``` @@ -94,9 +97,9 @@ items.sort((a, b) => a.localeCompare(b, 'fr', { ignorePunctuation: true })); ```js function localeCompareSupportsLocales() { try { - 'foo'.localeCompare('bar', 'i'); + "foo".localeCompare("bar", "i"); } catch (e) { - return e.name === 'RangeError'; + return e.name === "RangeError"; } return false; } @@ -109,8 +112,8 @@ function localeCompareSupportsLocales() { 為了讓回傳結果依照特定語言來排序,請確保使用 `locales` 參數指定該語言(可能還要再加上其他後備語言): ```js -console.log('ä'.localeCompare('z', 'de')); // 回傳負數:在德文, ä 的順序在 z 之前 -console.log('ä'.localeCompare('z', 'sv')); // 回傳正數:在瑞典文, ä 的順序在 z 之後 +console.log("ä".localeCompare("z", "de")); // 回傳負數:在德文, ä 的順序在 z 之前 +console.log("ä".localeCompare("z", "sv")); // 回傳正數:在瑞典文, ä 的順序在 z 之後 ``` ### 使用 `options` @@ -119,9 +122,9 @@ console.log('ä'.localeCompare('z', 'sv')); // 回傳正數:在瑞典文, ä ```js // 在德文, ä 和 a 是相同字母 -console.log('ä'.localeCompare('a', 'de', { sensitivity: 'base' })); // 0 +console.log("ä".localeCompare("a", "de", { sensitivity: "base" })); // 0 // 在瑞典文, ä 和 a 是各自獨立的字母 -console.log('ä'.localeCompare('a', 'sv', { sensitivity: 'base' })); // 回傳正數 +console.log("ä".localeCompare("a", "sv", { sensitivity: "base" })); // 回傳正數 ``` ### 數字排序 diff --git a/files/zh-tw/web/javascript/reference/global_objects/string/match/index.md b/files/zh-tw/web/javascript/reference/global_objects/string/match/index.md index 444d0a95378f4c..cfdf45b338085b 100644 --- a/files/zh-tw/web/javascript/reference/global_objects/string/match/index.md +++ b/files/zh-tw/web/javascript/reference/global_objects/string/match/index.md @@ -9,7 +9,7 @@ The **`match()`** method retrieves the matches when matching a _string_ against ## Syntax -```plain +```js-nolint str.match(regexp) ``` @@ -41,7 +41,7 @@ If the regular expression includes the `g` flag, the method returns an {{jsxref( 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. ```js -var str = 'For more information, see Chapter 3.4.5.1'; +var str = "For more information, see Chapter 3.4.5.1"; var re = /see (chapter \d+(\.\d)*)/i; var found = str.match(re); @@ -65,7 +65,7 @@ console.log(found); 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. ```js -var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; +var str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; var regexp = /[A-E]/gi; var matches_array = str.match(regexp); @@ -78,7 +78,7 @@ console.log(matches_array); ```js var str = "Nothing will come of nothing."; -str.match(); // returns [""] +str.match(); // returns [""] ``` ### A non-RegExp object as the parameter @@ -86,17 +86,18 @@ str.match(); // returns [""] 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. ```js -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"] +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 diff --git a/files/zh-tw/web/javascript/reference/global_objects/string/padstart/index.md b/files/zh-tw/web/javascript/reference/global_objects/string/padstart/index.md index 5d0e44e236c39b..1170ef953b3995 100644 --- a/files/zh-tw/web/javascript/reference/global_objects/string/padstart/index.md +++ b/files/zh-tw/web/javascript/reference/global_objects/string/padstart/index.md @@ -9,7 +9,7 @@ slug: Web/JavaScript/Reference/Global_Objects/String/padStart ## Syntax -```plain +```js-nolint str.padStart(targetLength [, padString]) ``` @@ -27,9 +27,9 @@ str.padStart(targetLength [, padString]) ## Examples ```js -'abc'.padStart(10); // " abc" -'abc'.padStart(10, "foo"); // "foofoofabc" -'abc'.padStart(6,"123465"); // "123abc" +"abc".padStart(10); // " abc" +"abc".padStart(10, "foo"); // "foofoofabc" +"abc".padStart(6, "123465"); // "123abc" ``` ## 規範 @@ -40,6 +40,6 @@ str.padStart(targetLength [, padString]) {{Compat}} -## See also +## 參見 - {{jsxref("String.padEnd()")}} diff --git a/files/zh-tw/web/javascript/reference/global_objects/string/replace/index.md b/files/zh-tw/web/javascript/reference/global_objects/string/replace/index.md index f5826579d1bbe2..7ab80c5dd37732 100644 --- a/files/zh-tw/web/javascript/reference/global_objects/string/replace/index.md +++ b/files/zh-tw/web/javascript/reference/global_objects/string/replace/index.md @@ -11,7 +11,7 @@ slug: Web/JavaScript/Reference/Global_Objects/String/replace ## 語法 -```plain +```js-nolint str.replace(regexp|substr, newSubstr|function) ``` @@ -40,12 +40,12 @@ To perform a global search and replace, include the `g` switch in the regular ex The replacement string can include the following special replacement patterns: -| Pattern | Inserts | -| -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `$$` | 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. | +| Pattern | Inserts | +| -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `$$` | 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. | | `$n` | Where `n` is a positive integer less than 100, inserts the *n*th parenthesized submatch string, provided the first argument was a {{jsxref("RegExp")}} object. | ### 指定一個函式為參數 @@ -54,12 +54,12 @@ You can specify a function as the second parameter. In this case, the function w The arguments to the function are as follows: -| Possible name | Supplied value | -| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `match` | The matched substring. (Corresponds to `$&` above.) | +| Possible name | Supplied value | +| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `match` | The matched substring. (Corresponds to `$&` above.) | | `p1, p2, ...` | The *n*th 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+`. | -| `offset` | The 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.) | -| `string` | The whole string being examined. | +| `offset` | The 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.) | +| `string` | The 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.) @@ -68,10 +68,10 @@ The following example will set `newString` to `'abc - 12345 - #$*%'`: ```js function replacer(match, p1, p2, p3, offset, string) { // p1 is nondigits, p2 digits, and p3 non-alphanumerics - return [p1, p2, p3].join(' - '); + return [p1, p2, p3].join(" - "); } -var newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer); -console.log(newString); // abc - 12345 - #$*% +var newString = "abc12345#$*%".replace(/([^\d]*)(\d*)([^\w]*)/, replacer); +console.log(newString); // abc - 12345 - #$*% ``` ## 範例 @@ -81,9 +81,9 @@ console.log(newString); // abc - 12345 - #$*% 下例的正規表達式被定義為 `replace()`、並包含了忽略大小寫的 flag。 ```js -var str = 'Twas the night before Xmas...'; -var newstr = str.replace(/xmas/i, 'Christmas'); -console.log(newstr); // Twas the night before Christmas... +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...」 @@ -94,9 +94,9 @@ Global replace can only be done with a regular expression. In the following exam ```js 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. +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」。 @@ -107,9 +107,9 @@ console.log(newstr); // oranges are round, and oranges are juicy. ```js var re = /(\w+)\s(\w+)/; -var str = 'John Smith'; -var newstr = str.replace(re, '$2, $1'); -console.log(newstr); // Smith, John +var str = "John Smith"; +var newstr = str.replace(re, "$2, $1"); +console.log(newstr); // Smith, John ``` 上例會顯示「Smith, John」。 @@ -123,7 +123,7 @@ The replacement function accepts the matched snippet as its parameter, and uses ```js function styleHyphenFormat(propertyName) { function upperToHyphenLower(match, offset, string) { - return (offset ? '-' : '') + match.toLowerCase(); + return (offset ? "-" : "") + match.toLowerCase(); } return propertyName.replace(/[A-Z]/g, upperToHyphenLower); } @@ -134,7 +134,7 @@ 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. ```js -var newString = propertyName.replace(/[A-Z]/g, '-' + '$&'.toLowerCase()); // won't work +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. @@ -148,7 +148,7 @@ The regular expression `test` checks for any number that ends with F. The number ```js function f2c(x) { function convert(str, p1, offset, s) { - return ((p1 - 32) * 5/9) + 'C'; + return ((p1 - 32) * 5) / 9 + "C"; } var s = String(x); var test = /(-?\d+(?:\.\d*)?)F\b/g; @@ -188,11 +188,15 @@ An array of objects. An `'x'` denotes an `'on'` state, a `'-'` (hyphen) denotes **Snippet:** ```js -var str = 'x-x_'; +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 }); } +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); diff --git a/files/zh-tw/web/javascript/reference/global_objects/string/tolowercase/index.md b/files/zh-tw/web/javascript/reference/global_objects/string/tolowercase/index.md index 3d8602d579ca07..1632da3b53f620 100644 --- a/files/zh-tw/web/javascript/reference/global_objects/string/tolowercase/index.md +++ b/files/zh-tw/web/javascript/reference/global_objects/string/tolowercase/index.md @@ -11,7 +11,7 @@ slug: Web/JavaScript/Reference/Global_Objects/String/toLowerCase ## 语法 -```plain +```js-nolint str.toLowerCase() ``` @@ -25,10 +25,10 @@ The `toLowerCase()` 函式会回传一组将原字符串英文内容转换成英 ## 范例 -### 使用`toLowerCase()` +### 使用 `toLowerCase()` ```js -console.log('ALPHABET'.toLowerCase()); // 'alphabet' +console.log("ALPHABET".toLowerCase()); // 'alphabet' ``` ## 规范 @@ -39,7 +39,7 @@ console.log('ALPHABET'.toLowerCase()); // 'alphabet' {{Compat}} -## 参考 +## 參見 - {{jsxref("String.prototype.toLocaleLowerCase()")}} - {{jsxref("String.prototype.toLocaleUpperCase()")}} diff --git a/files/zh-tw/web/javascript/reference/global_objects/string/trim/index.md b/files/zh-tw/web/javascript/reference/global_objects/string/trim/index.md index f3e108de11d1e9..b6589e769f2613 100644 --- a/files/zh-tw/web/javascript/reference/global_objects/string/trim/index.md +++ b/files/zh-tw/web/javascript/reference/global_objects/string/trim/index.md @@ -12,7 +12,7 @@ slug: Web/JavaScript/Reference/Global_Objects/String/trim ## 語法 -```js +```js-nolint trim() ``` @@ -31,7 +31,7 @@ trim() ```js if (!String.prototype.trim) { String.prototype.trim = function () { - return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); + return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ""); }; } ``` @@ -43,11 +43,11 @@ if (!String.prototype.trim) { 以下例子會印出小寫的字串 `'foo'`: ```js -var orig = ' foo '; +var orig = " foo "; console.log(orig.trim()); // 'foo' ``` -## 規格 +## 規範 {{Specifications}} diff --git a/files/zh-tw/web/javascript/reference/global_objects/typedarray/index.md b/files/zh-tw/web/javascript/reference/global_objects/typedarray/index.md index e4e8eb3ccfb500..852c05d8d03cb8 100644 --- a/files/zh-tw/web/javascript/reference/global_objects/typedarray/index.md +++ b/files/zh-tw/web/javascript/reference/global_objects/typedarray/index.md @@ -60,33 +60,33 @@ 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 +Int8Array.prototype[20] = "foo"; +new Int8Array(32)[20]; // 0 // even when out of bound -Int8Array.prototype[20] = 'foo'; -(new Int8Array(8))[20]; // undefined +Int8Array.prototype[20] = "foo"; +new Int8Array(8)[20]; // undefined // or with negative integers -Int8Array.prototype[-1] = 'foo'; -(new Int8Array(8))[-1]; // undefined +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" +Int8Array.prototype.foo = "bar"; +new Int8Array(32).foo; // "bar" ``` ## TypedArray 物件 -| Type | Value Range | Size in bytes | Description | Web IDL type | Equivalent C type | -| ---------------------------------------- | ------------------------- | ------------- | ------------------------------------------------------------------------- | --------------------- | ----------------- | +| Type | Value Range | Size in bytes | Description | Web IDL type | Equivalent C type | +| ------------------------------- | ------------------------- | ------------- | ------------------------------------------------------------------------- | --------------------- | ----------------- | | {{jsxref("Int8Array")}} | -128 to 127 | 1 | 8-bit two's complement signed integer | `byte` | `int8_t` | -| {{jsxref("Uint8Array")}} | 0 to 255 | 1 | 8-bit unsigned integer | `octet` | `uint8_t` | +| {{jsxref("Uint8Array")}} | 0 to 255 | 1 | 8-bit unsigned integer | `octet` | `uint8_t` | | {{jsxref("Uint8ClampedArray")}} | 0 to 255 | 1 | 8-bit unsigned integer (clamped) | `octet` | `uint8_t` | -| {{jsxref("Int16Array")}} | -32768 to 32767 | 2 | 16-bit two's complement signed integer | `short` | `int16_t` | -| {{jsxref("Uint16Array")}} | 0 to 65535 | 2 | 16-bit unsigned integer | `unsigned short` | `uint16_t` | -| {{jsxref("Int32Array")}} | -2147483648 to 2147483647 | 4 | 32-bit two's complement signed integer | `long` | `int32_t` | -| {{jsxref("Uint32Array")}} | 0 to 4294967295 | 4 | 32-bit unsigned integer | `unsigned long` | `uint32_t` | -| {{jsxref("Float32Array")}} | 1.2x10^-38 to 3.4x10^38 | 4 | 32-bit IEEE floating point number ( 7 significant digits e.g. 1.1234567) | `unrestricted float` | `float` | -| {{jsxref("Float64Array")}} | 5.0x10^-324 to 1.8x10^308 | 8 | 64-bit IEEE floating point number (16 significant digits e.g. 1.123...15) | `unrestricted double` | `double` | +| {{jsxref("Int16Array")}} | -32768 to 32767 | 2 | 16-bit two's complement signed integer | `short` | `int16_t` | +| {{jsxref("Uint16Array")}} | 0 to 65535 | 2 | 16-bit unsigned integer | `unsigned short` | `uint16_t` | +| {{jsxref("Int32Array")}} | -2147483648 to 2147483647 | 4 | 32-bit two's complement signed integer | `long` | `int32_t` | +| {{jsxref("Uint32Array")}} | 0 to 4294967295 | 4 | 32-bit unsigned integer | `unsigned long` | `uint32_t` | +| {{jsxref("Float32Array")}} | 1.2x10^-38 to 3.4x10^38 | 4 | 32-bit IEEE floating point number ( 7 significant digits e.g. 1.1234567) | `unrestricted float` | `float` | +| {{jsxref("Float64Array")}} | 5.0x10^-324 to 1.8x10^308 | 8 | 64-bit IEEE floating point number (16 significant digits e.g. 1.123...15) | `unrestricted double` | `double` | ## 屬性 @@ -200,14 +200,25 @@ These methods are defined on the `TypedArray` prototype object and are thus shar 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. ```js example-bad -var typedArrayTypes = [Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, - Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array]; +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]; + for (var v in Array.prototype) + if ( + Array.prototype.hasOwnProperty(v) && + !typedArrayTypes[k].prototype.hasOwnProperty(v) + ) + typedArrayTypes[k].prototype[v] = Array.prototype[v]; ``` ## 規範