From 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:43:23 -0500 Subject: initial commit --- .../reference/statements/async_function/index.html | 255 +++++++++++++++++ .../reference/statements/continue/index.html | 135 +++++++++ .../reference/statements/do...while/index.html | 98 +++++++ .../reference/statements/export/index.html | 186 ++++++++++++ .../reference/statements/for...of/index.html | 318 +++++++++++++++++++++ .../javascript/reference/statements/for/index.html | 137 +++++++++ .../reference/statements/function_star_/index.html | 208 ++++++++++++++ .../web/javascript/reference/statements/index.html | 143 +++++++++ .../reference/statements/throw/index.html | 193 +++++++++++++ 9 files changed, 1673 insertions(+) create mode 100644 files/vi/web/javascript/reference/statements/async_function/index.html create mode 100644 files/vi/web/javascript/reference/statements/continue/index.html create mode 100644 files/vi/web/javascript/reference/statements/do...while/index.html create mode 100644 files/vi/web/javascript/reference/statements/export/index.html create mode 100644 files/vi/web/javascript/reference/statements/for...of/index.html create mode 100644 files/vi/web/javascript/reference/statements/for/index.html create mode 100644 files/vi/web/javascript/reference/statements/function_star_/index.html create mode 100644 files/vi/web/javascript/reference/statements/index.html create mode 100644 files/vi/web/javascript/reference/statements/throw/index.html (limited to 'files/vi/web/javascript/reference/statements') diff --git a/files/vi/web/javascript/reference/statements/async_function/index.html b/files/vi/web/javascript/reference/statements/async_function/index.html new file mode 100644 index 0000000000..3009b78083 --- /dev/null +++ b/files/vi/web/javascript/reference/statements/async_function/index.html @@ -0,0 +1,255 @@ +--- +title: async function +slug: Web/JavaScript/Reference/Statements/async_function +translation_of: Web/JavaScript/Reference/Statements/async_function +--- +
+
{{jsSidebar("Statements")}}
+Việc tạo hàm với câu lệnh async function sẽ định nghĩa ra một hàm không đồng bộ (asynchronous function) - hàm này sẽ trả về một object {{jsxref("Global_Objects/AsyncFunction","AsyncFunction")}}
+ +

Các hàm không đồng bộ sẽ hoạt động trong một thứ tự tách biệt so với phần còn lại của đoạn code thông qua một event loop, trả về kết quả là một {{jsxref("Promise")}} tiềm ẩn. Nhưng cú pháp và cấu trúc của đoạn code mà sử dụng các hàm async function trông cứ như những hàm đồng bộ tiêu chuẩn.

+ +
+

Bạn cũng có thể định nghĩa các async function với một {{jsxref("Operators/async_function", "async function expression", "", 1)}}.

+
+
+ +
{{EmbedInteractiveExample("pages/js/statement-async.html", "taller")}}
+ + + +

Cú pháp

+ +
async function name([param[, param[, ...param]]]) {
+   statements
+}
+
+ +

Các thông số

+ +
+
name
+
Tên của function.
+
param
+
Tên của một đối số được truyền vào function.
+
statements
+
Các câu lệnh bao hàm phần thân của function.
+
+ +

Giá trị trả về

+ +

Một Promise, cái mà sẽ được giải quyết với giá trị được trả về bởi async function, hoặc được đẩy ra ngoài với một exception không được bắt lại bên trong hàm async function.

+ +

Mô tả

+ +

Một hàm async có thể bao gồm một biểu thức {{jsxref("Operators/await", "await")}}, biểu thức này sẽ tạm dừng việc thực thi của hàm async để chờ cho Promise's resolution được truyền vào, sau đó tiếp tục việc thực thi của hàm async and evaluates as the resolved value.

+ +

Từ khóa await chỉ có hiệu lực bên trong hàm async. Nếu bạn sử dụng nó bên ngoài phần thân của hàm async, bạn sẽ nhận một SyntaxError.

+ +

Trong lúc hàm async tạm dừng, hàm được gọi sẽ tiếp tục chạy. (hàm mà nhận được Promise tiềm ẩn được trả về bởi hàm async).

+ +
+

Mục đích của async/await là để đơn giả hóa việc sử dụng các promises một cách đồng bộ, và để triển khai một số hoạt động trên một nhóm của các Promises. Nếu Promises là tương tự như các callback có cấu trúc, async/await là tương tự với kết hợp các generators và promises.

+
+ +

Ví dụ

+ +

Async functions và thứ tự của việc thực thi

+ +
function resolveAfter2Seconds() {
+  console.log("starting slow promise")
+  return new Promise(resolve => {
+    setTimeout(function() {
+      resolve("slow")
+      console.log("slow promise is done")
+    }, 2000)
+  })
+}
+
+function resolveAfter1Second() {
+  console.log("starting fast promise")
+  return new Promise(resolve => {
+    setTimeout(function() {
+      resolve("fast")
+      console.log("fast promise is done")
+    }, 1000)
+  })
+}
+
+async function sequentialStart() {
+  console.log('==SEQUENTIAL START==')
+
+  // 1. Execution gets here almost instantly
+  const slow = await resolveAfter2Seconds()
+  console.log(slow) // 2. this runs 2 seconds after 1.
+
+  const fast = await resolveAfter1Second()
+  console.log(fast) // 3. this runs 3 seconds after 1.
+}
+
+async function concurrentStart() {
+  console.log('==CONCURRENT START with await==');
+  const slow = resolveAfter2Seconds() // starts timer immediately
+  const fast = resolveAfter1Second() // starts timer immediately
+
+  // 1. Execution gets here almost instantly
+  console.log(await slow) // 2. this runs 2 seconds after 1.
+  console.log(await fast) // 3. this runs 2 seconds after 1., immediately after 2., since fast is already resolved
+}
+
+function concurrentPromise() {
+  console.log('==CONCURRENT START with Promise.all==')
+  return Promise.all([resolveAfter2Seconds(), resolveAfter1Second()]).then((messages) => {
+    console.log(messages[0]) // slow
+    console.log(messages[1]) // fast
+  })
+}
+
+async function parallel() {
+  console.log('==PARALLEL with await Promise.all==')
+
+  // Start 2 "jobs" in parallel and wait for both of them to complete
+  await Promise.all([
+      (async()=>console.log(await resolveAfter2Seconds()))(),
+      (async()=>console.log(await resolveAfter1Second()))()
+  ])
+}
+
+// This function does not handle errors. See warning below!
+function parallelPromise() {
+  console.log('==PARALLEL with Promise.then==')
+  resolveAfter2Seconds().then((message)=>console.log(message))
+  resolveAfter1Second().then((message)=>console.log(message))
+}
+
+sequentialStart() // after 2 seconds, logs "slow", then after 1 more second, "fast"
+
+// wait above to finish
+setTimeout(concurrentStart, 4000) // after 2 seconds, logs "slow" and then "fast"
+
+// wait again
+setTimeout(concurrentPromise, 7000) // same as concurrentStart
+
+// wait again
+setTimeout(parallel, 10000) // truly parallel: after 1 second, logs "fast", then after 1 more second, "slow"
+
+// wait again
+setTimeout(parallelPromise, 13000) // same as parallel
+
+ +

await và xử lý song song

+ +

In sequentialStart, execution suspends 2 seconds for the first await, and then another second for the second await. The second timer is not created until the first has already fired, so the code finishes after 3 seconds.

+ +

In concurrentStart, both timers are created and then awaited. The timers run concurrently, which means the code finishes in 2 rather than 3 seconds, i.e. the slowest timer.
+ However, the await calls still run in series, which means the second await will wait for the first one to finish. In this case, the result of the fastest timer is processed after the slowest.

+ +

If you wish to fully perform two or more jobs in parallel, you must use await Promise.all([job1(), job2()]), as shown in the parallel example.

+ +
+

async/await vs Promise.then and error handling

+ +

Most async functions can also be written as regular functions using Promises. However, async functions are less tricky when it comes to error handling.

+ +

Both concurrentStart and concurrentPromise are functionally equivalent:

+ + + +

It is, however, still possible for async functions to mistakenly swallow errors.

+ +

Take, for example the parallel async function. If it didn't await (or return) the result of the Promise.all([]) call, any Error would not propagate.

+ +

While the parallelPromise example seems simpler, it does not handle errors at all! Doing so would require a similar return Promise.all([]).

+
+ +

Rewriting a Promise chain with an async function

+ +

An API that returns a {{jsxref("Promise")}} will result in a promise chain, and it splits the function into many parts. Consider the following code:

+ +
function getProcessedData(url) {
+  return downloadData(url) // returns a promise
+    .catch(e => {
+      return downloadFallbackData(url)  // returns a promise
+    })
+    .then(v => {
+      return processDataInWorker(v)  // returns a promise
+    })
+}
+
+ +

it can be rewritten with a single async function as follows:

+ +
async function getProcessedData(url) {
+  let v
+  try {
+    v = await downloadData(url)
+  } catch(e) {
+    v = await downloadFallbackData(url)
+  }
+  return processDataInWorker(v)
+}
+
+ +

In the above example, there is no await statement after the return keyword, because the return value of an async function is implicitly wrapped in {{jsxref("Promise.resolve")}}.

+ +
+

return await promiseValue vs. return promiseValue

+ +

The implicit wrapping of return values in {{jsxref("Promise.resolve")}} does not imply that return await promiseValue is functionally equivalent to return promiseValue.

+ +

Consider the following rewrite of the above code. It returns null if processDataInWorker rejects with an error:

+ +
async function getProcessedData(url) {
+  let v
+  try {
+    v = await downloadData(url)
+  } catch(e) {
+    v = await downloadFallbackData(url)
+  }
+  try {
+    return await processDataInWorker(v)  // Note the `return await` vs. just `return`
+  } catch (e) {
+    return null
+  }
+}
+
+ +

Writing return processDataInWorker(v) would have caused the {{jsxref("Promise")}} returned by the function to reject, instead of resolving to null if processDataInWorker(v) rejects.

+ +

This highlights the subtle difference between return foo; and return await foo;return foo immediately returns foo and never throws, even if foo is a Promise that rejects. return await foo will wait for foo to resolve or reject if it's a Promise, and throws before returning if it rejects.

+
+ +

Specifications

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-async-function-definitions', 'async function')}}
+ +

Browser compatibility

+ +
+ + +

{{Compat("javascript.statements.async_function")}}

+
+ +

See also

+ + diff --git a/files/vi/web/javascript/reference/statements/continue/index.html b/files/vi/web/javascript/reference/statements/continue/index.html new file mode 100644 index 0000000000..d6afd506d7 --- /dev/null +++ b/files/vi/web/javascript/reference/statements/continue/index.html @@ -0,0 +1,135 @@ +--- +title: continue +slug: Web/JavaScript/Reference/Statements/continue +translation_of: Web/JavaScript/Reference/Statements/continue +--- +
{{jsSidebar("Statements")}}
+ +

Câu lệnh continue chấm dứt việc thực thi của các câu lệnh trong lượt lặp hiện tại của vòng lặp hiện tại, hoặc của vòng lặp được gắn nhãn, và tiếp tục việc thực thi lượt lặp kế tiếp.

+ +
{{EmbedInteractiveExample("pages/js/statement-continue.html")}}
+ + + +

Cú pháp

+ +
continue [label];
+ +
+
label
+
Identifier gắn liền với nhãn của câu lệnh.
+
+ +

Mô tả

+ +

Trái ngược với câu lệnh {{jsxref("Statements/break", "break")}}, continue không chấm dứt việc thực thi của cả vòng lặp: thay vào đó,

+ + + +

Câu lệnh continue có thể bao gồm một nhãn tùy chọn cho phép chương trình nhảy đến lượt lặp tiếp theo của một câu lệnh vòng lặp được gắn nhãn, thay vì nhảy đến lượt lặp tiếp theo của vòng lặp hiện tại. Trong trường hợp này, câu lệnh continue cần được lồng bên trong câu lệnh được gắn nhãn đó.

+ +

Ví dụ

+ +

Sử dụng continue với while

+ +

Ví dụ sau thể hiện một vòng lặp {{jsxref("Statements/while", "while")}} có một câu lệnh continue mà sẽ được thực thi khi giá trị của i là 3. Vì vậy, n nhận các giá trị 1, 3, 7 và 12.

+ +
var i = 0;
+var n = 0;
+
+while (i < 5) {
+  i++;
+
+  if (i === 3) {
+    continue;
+  }
+
+  n += i;
+}
+
+ +

Sử dụng continue với một nhãn (label)

+ +

Trong ví dụ sau đây, một câu lệnh được gắn nhãn checkiandj có chứa một câu lệnh được gắn nhãn checkj. Nếu gặp phải continue, chương trình sẽ tiếp tục tại phần đầu của câu lệnh checkj. Mỗi lần gặp phải continuecheckj sẽ chạy lại cho đến khi điều kiện của nó trả về false. Khi false được trả về, phần còn lại của câu lệnh checkiandj sẽ được hoàn thành.

+ +

Nếu sau continue có một nhãn checkiandj, chương trình sẽ tiếp túc tại phần đầu của câu lệnh checkiandj.

+ +

Xem thêm {{jsxref("Statements/label", "label")}}.

+ +
var i = 0;
+var j = 8;
+
+checkiandj: while (i < 4) {
+  console.log('i: ' + i);
+  i += 1;
+
+  checkj: while (j > 4) {
+    console.log('j: ' + j);
+    j -= 1;
+
+    if ((j % 2) == 0)
+      continue checkj;
+    console.log(j + ' is odd.');
+  }
+  console.log('i = ' + i);
+  console.log('j = ' + j);
+}
+
+ +

Kết quả:

+ +
i: 0
+
+// start checkj
+j: 8
+7 is odd.
+j: 7
+j: 6
+5 is odd.
+j: 5
+// end checkj
+
+i = 1
+j = 4
+
+i: 1
+i = 2
+j = 4
+
+i: 2
+i = 3
+j = 4
+
+i: 3
+i = 4
+j = 4
+
+ +

Specifications

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-continue-statement', 'Continue statement')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.statements.continue")}}

+ +

See also

+ + diff --git a/files/vi/web/javascript/reference/statements/do...while/index.html b/files/vi/web/javascript/reference/statements/do...while/index.html new file mode 100644 index 0000000000..eef8cf1f08 --- /dev/null +++ b/files/vi/web/javascript/reference/statements/do...while/index.html @@ -0,0 +1,98 @@ +--- +title: do...while +slug: Web/JavaScript/Reference/Statements/do...while +translation_of: Web/JavaScript/Reference/Statements/do...while +--- +
{{jsSidebar("Statements")}}
+ +

Vòng lặp do...while tạo ra vòng lặp thực thi các câu lệnh bên trong nó đến khi điều kiện không còn thoả mãn nữa. Điều kiện của vòng lặp sẽ được kiểm tra sau thực thi các câu lệnh, các câu lệnh của vòng lặp sẽ được thực thi ít nhất một lần.

+ +
{{EmbedInteractiveExample("pages/js/statement-dowhile.html")}}
+ + + +

Cú pháp

+ +
do
+   // các câu lệnh
+while (// điều kiện);
+
+ +
+
statement
+
A statement that is executed at least once and is re-executed each time the condition evaluates to true. To execute multiple statements within the loop, use a {{jsxref("Statements/block", "block")}} statement ({ ... }) to group those statements.
+
+ +
+
condition
+
An expression evaluated after each pass through the loop. If condition evaluates to true, the statement is re-executed. When condition evaluates to false, control passes to the statement following the do...while.
+
+ +

Examples

+ +

Using do...while

+ +

In the following example, the do...while loop iterates at least once and reiterates until i is no longer less than 5.

+ +

HTML content

+ +
<div id="example"></div>
+ +

JavaScript content

+ +
var result = '';
+var i = 0;
+do {
+   i += 1;
+   result += i + ' ';
+} while (i < 5);
+document.getElementById('example').innerHTML = result;
+ +

Result

+ +

{{ EmbedLiveSample('Examples') }}

+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2
{{SpecName('ES5.1', '#sec-12.6.1', 'do-while statement')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-do-while-statement', 'do-while statement')}}{{Spec2('ES6')}}Trailing ; is now optional.
{{SpecName('ESDraft', '#sec-do-while-statement', 'do-while statement')}}{{Spec2('ESDraft')}}
+ +

Browser compatibility

+ + + +

{{Compat("javascript.statements.do_while")}}

+ +

See also

+ + diff --git a/files/vi/web/javascript/reference/statements/export/index.html b/files/vi/web/javascript/reference/statements/export/index.html new file mode 100644 index 0000000000..0187b3dbfa --- /dev/null +++ b/files/vi/web/javascript/reference/statements/export/index.html @@ -0,0 +1,186 @@ +--- +title: export +slug: Web/JavaScript/Reference/Statements/export +translation_of: Web/JavaScript/Reference/Statements/export +--- +
{{jsSidebar("Statements")}}
+ +

Lệnh export được sử dụng khi tạo các module JavaScript để export các hàm, đối tượng hoặc giá trị nguyên thủy trong module để chúng có thể được sử dụng bởi các chương trình khác bằng lệnh {{jsxref("Statements/import", "import")}}.

+ +
+

Tính năng này mới chỉ được triển khai trên Safari vào thời điểm hiện tại. Nó cũng được triển khai ở nhiều trình dịch (transpilers), ví dụ như Traceur Compiler, Babel hay Rollup.

+
+ +

Cú pháp

+ +
export { name1, name2, …, nameN };
+export { variable1 as name1, variable2 as name2, …, nameN };
+export let name1, name2, …, nameN; // còn có thể là var, function
+export let name1 = …, name2 = …, …, nameN; // còn có thể là var, const
+
+export default expression;
+export default function (…) { … } // còn có thể là class, function*
+export default function name1(…) { … } // còn có thể là class, function*
+export { name1 as default, … };
+
+export * from …;
+export { name1, name2, …, nameN } from …;
+export { import1 as name1, import2 as name2, …, nameN } from …;
+ +
+
nameN
+
Định danh được export (để có thể được import thông qua lệnh {{jsxref("Statements/import", "import")}} ở trong script khác).
+
+ +

Mô tả

+ +

Có nhiều kiểu export khác nhau. Mỗi kiểu tương ứng với một trong các cú pháp ở phía trên:

+ + + +

Export tên hữu ích khi dùng để export một vài giá trị. Khi import, có thể dùng cùng tên đó để truy xuất đến giá trị tương ứng.

+ +

Về export giá trị mặc định, chỉ có duy nhất một giá trị mặc định được export trên một module. Một giá trị được export mặc định có thể là một hàm, một lớp, một đối tượng hay bất cứ thứ gì khác. Giá trị này được coi là giá trị được export "chính" do nó sẽ là giá trị đơn giản nhất được import.

+ +

Export các giá trị mặc định: Cú pháp sau đây không export một giá trị được export mặc định từ module được import:

+ +
export * from …;
+ +

Nếu bạn muốn export giá trị mặc định, hãy dùng cú pháp sau:

+ +
import mod from "mod";
+export default mod;
+ +

Ví dụ

+ +

Sử dụng export tên

+ +

Trong module, chúng ta có thể dùng code sau:

+ +
// module "my-module.js"
+function cube(x) {
+  return x * x * x;
+}
+const foo = Math.PI + Math.SQRT2;
+export { cube, foo };
+
+ +

Với cách này, trong script khác (cf. import), chúng ta có:

+ +
import { cube, foo } from 'my-module';
+console.log(cube(3)); // 27
+console.log(foo);    // 4.555806215962888
+ +

Sử dụng export giá trị mặc định

+ +

Nếu chúng ta muốn export một giá trị duy nhất hay có một giá trị trả về mặc định từ module của mình, chúng ta có thể sử dụng export giá trị mặc định:

+ +
// module "my-module.js"
+export default function cube(x) {
+  return x * x * x;
+}
+
+ +

Sau đó, trong script khác, có thể import thẳng giá trị được export mặc định:

+ +
import cube from 'my-module';
+console.log(cube(3)); // 27
+
+ +

Chú ý là không thể dùng var, let hay const với export default.

+ +

Đặc tả

+ + + + + + + + + + + + + + + + + + + +
Đặc tảTrạng tháiChú thích
{{SpecName('ES2015', '#sec-exports', 'Exports')}}{{Spec2('ES2015')}}Định nghĩa ban đầu.
{{SpecName('ESDraft', '#sec-exports', 'Exports')}}{{Spec2('ESDraft')}} 
+ +

Tương thích với trình duyệt

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
Tính năngChromeFirefox (Gecko)Internet ExplorerOperaSafari
Hỗ trợ cơ bản61 (60 w/ flag){{CompatNo}} (54 w/ flag){{CompatNo}} (15 w/flag){{CompatNo}}10.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
Tính năngAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Hỗ trợ cơ bản{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}10.3
+
+ +

Xem thêm

+ + diff --git a/files/vi/web/javascript/reference/statements/for...of/index.html b/files/vi/web/javascript/reference/statements/for...of/index.html new file mode 100644 index 0000000000..5bd72040eb --- /dev/null +++ b/files/vi/web/javascript/reference/statements/for...of/index.html @@ -0,0 +1,318 @@ +--- +title: for...of +slug: Web/JavaScript/Reference/Statements/for...of +tags: + - ECMAScript 2015 + - JavaScript + - Reference + - Statement +translation_of: Web/JavaScript/Reference/Statements/for...of +--- +
{{jsSidebar("Statements")}}
+ +

Cú pháp for...of để chạy vòng lặp trên {{jsxref("String")}}, {{jsxref("Array")}}, đối tượng tương tự Array (như {{jsxref("Functions/arguments", "arguments")}} hoặc {{domxref("NodeList")}}), {{jsxref("TypedArray")}}, {{jsxref("Map")}}, {{jsxref("Set")}}.

+ +
{{EmbedInteractiveExample("pages/js/statement-forof.html")}}
+ + + +

Cú pháp

+ +
for (tên-biến of đối-tượng-chạy-vòng-lặp) {
+  ...câu lệnh...
+}
+
+ +
+
tên biến
+

+ Trên mỗi lần lặp, một giá trị của một thuộc tính khác nhau được gán cho biến. biến có thể được khai báo với const, let hoặc var.
+
đối tượng để chạy vòng lặp
+
Đối tượng có các thuộc tính có thể được lặp lại (iterable).
+
+ +

Ví dụ

+ +

Lặp qua một {{jsxref("Array")}}

+ +
let iterable = [10, 20, 30];
+
+for (let value of iterable ) {
+  value += 1;
+  console.log(value);
+}
+// 11
+// 21
+// 31
+
+ +

Có thể khai báo bằng const thay cho let, nếu không có thay đổi biến bên trong vòng lặp.

+ +
let iterable= [10, 20, 30];
+
+for (const value of iterable) {
+  console.log(value);
+}
+// 10
+// 20
+// 30
+
+ +

Lặp qua một {{jsxref("String")}}

+ +
const iterable = 'boo';
+
+for (const value of iterable) {
+  console.log(value);
+}
+// "b"
+// "o"
+// "o"
+
+ +

Lặp qua {{jsxref("TypedArray")}}

+ +
const iterable = new Uint8Array([0x00, 0xff]);
+
+for (const value of iterable) {
+  console.log(value);
+}
+// 0
+// 255
+
+ +

Lặp qua một {{jsxref("Map")}}

+ +
const iterable = new Map([['a', 1], ['b', 2], ['c', 3]]);
+
+for (const entry of iterable) {
+  console.log(entry);
+}
+// ['a', 1]
+// ['b', 2]
+// ['c', 3]
+
+for (const [key, value] of iterable) {
+  console.log(value);
+}
+// 1
+// 2
+// 3
+
+ +

Loop qua một {{jsxref("Set")}}

+ +
const iterable = new Set([1, 1, 2, 2, 3, 3]);
+
+for (const value of iterable) {
+  console.log(value);
+}
+// 1
+// 2
+// 3
+
+ +

Lặp qua một đối tượng arguments

+ +

Lặp qua đối tượng {{jsxref("Functions/arguments", "arguments")}} để có tất cả giá trị được truyền vào trong hàm:

+ +
(function() {
+  for (const argument of arguments) {
+    console.log(argument);
+  }
+})(1, 2, 3);
+
+// 1
+// 2
+// 3
+ +

Lặp qua một tập DOM

+ +

Lặp qua một tập DOM như {{domxref("NodeList")}}: ví dụ bên dưới, thêm class read cho các đoạn văn bản nào là con trực tiếp của article:

+ +
// Lưu ý: Chỉ hoạt động động trên các platforms có
+// hiện thực NodeList.prototype[Symbol.iterator]
+const articleParagraphs = document.querySelectorAll('article > p');
+
+for (const paragraph of articleParagraphs) {
+  paragraph.classList.add('read');
+}
+
+ +

Đóng vòng lặp

+ +

Trong vòng lặp for...of, có thể ngừng lặp giữa chừng bằng break, continue, throw hoặc return. Trong các trường hợp này, vòng lặp sẽ được ngưng lại.

+ +
function* foo(){
+  yield 1;
+  yield 2;
+  yield 3;
+};
+
+for (const o of foo()) {
+  console.log(o);
+  break; // đóng vòng lặp, tiếp tục thực thi bên ngoài vòng lặp
+}
+console.log('Xong')
+
+ +

Lặp qua generator

+ +

Bạn cũng có thể lặp qua hàm generators, ví dụ:

+ +
function* fibonacci() { // một hàm generator
+  let [prev, curr] = [0, 1];
+  while (true) {
+    [prev, curr] = [curr, prev + curr];
+    yield curr;
+  }
+}
+
+for (const n of fibonacci()) {
+  console.log(n);
+  // truncate the sequence at 1000
+  if (n >= 1000) {
+    break;
+  }
+}
+
+ +

Không tái sử dụng generator

+ +

Không nên re-used Generator, ngay cả khi vòng lặp for...of bị kết thúc sớm bằng {{jsxref("Statements/break", "break")}}. Khi thoát khỏi vòng lặp, generator sẽ kết thúc và cố lặp lại lần nữa sẽ không cho thêm bất kỳ kết quả yield nào khác.

+ +
const gen = (function *(){
+  yield 1;
+  yield 2;
+  yield 3;
+})();
+for (const o of gen) {
+  console.log(o);
+  break;  // Closes iterator
+}
+
+// Không dùng lại generator, đoạn code như thế này không hợp lý!
+for (const o of gen) {
+  console.log(o); // Không bao giờ được gọi
+}
+
+ +

Lặp qua các đối tượng khác

+ +

Bạn cũng có thể loop qua các đối tượng tự định nghĩa, nếu có hiện thực iterable:

+ +
const iterable = {
+  [Symbol.iterator]() {
+    return {
+      i: 0,
+      next() {
+        if (this.i < 3) {
+          return { value: this.i++, done: false };
+        }
+        return { value: undefined, done: true };
+      }
+    };
+  }
+};
+
+for (const value of iterable) {
+  console.log(value);
+}
+// 0
+// 1
+// 2
+
+ +

Sự khác biệt giữa for...offor...in

+ +

Cú pháp {{jsxref("Statements/for...in", "for...in")}} lặp qua các đối tượng được đếm, theo một thứ tự tùy ý.

+ +

Cú pháp for...of lặp qua đối tượng dữ liệu có thể lặp.

+ +

Ví dụ sau để thấy sự khác nhau giữa for...of và for...in khi sử dụng với {{jsxref("Array")}}.

+ +
Object.prototype.objCustom = function() {};
+Array.prototype.arrCustom = function() {};
+
+const iterable = [3, 5, 7];
+iterable.foo = 'hello';
+
+for (const i in iterable) {
+  console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
+}
+
+for (const i in iterable) {
+  if (iterable.hasOwnProperty(i)) {
+    console.log(i); // logs 0, 1, 2, "foo"
+  }
+}
+
+for (const i of iterable) {
+  console.log(i); // logs 3, 5, 7
+}
+
+ +

Giải thích ví dụ trên

+ +
Object.prototype.objCustom = function() {};
+Array.prototype.arrCustom = function() {};
+
+const iterable = [3, 5, 7];
+iterable.foo = 'hello';
+ +

Tất cả object sẽ kế thừa thuộc tính objCustom và tất cả {{jsxref("Array")}} sẽ kết thừa thuộc tính arrCustom bởi vì chúng ta thêm nó vào bằng {{jsxref("Object.prototype")}} và {{jsxref("Array.prototype")}}. iterable kế thừa cả objCustomarrCustom.

+ +
for (const i in iterable) {
+  console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
+}
+ +

Vòng vòng lặp này chỉ log thuộc tính được đếm của iterable, theo thứ tự được đưa vào. Nó không log các element của array 3, 5, 7 hoặc hello bởi vì nó là không thuộc tính được đếm. Nó log giá trị index cũng như arrCustomobjCustom.

+ +
for (let i in iterable) {
+  if (iterable.hasOwnProperty(i)) {
+    console.log(i); // logs 0, 1, 2, "foo"
+  }
+}
+ +

Vòng loop tương tự như ở trên, nhưng sử dụng {{jsxref("Object.prototype.hasOwnProperty()", "hasOwnProperty()")}} để kiểm tra, nếu tìm thấy một property của chính nó chứ không phải kế thừa và log kết quả ra. Các Property 0, 1, 2foo được log bởi vì nó không phải được kết thừa.

+ +
for (const i of iterable) {
+  console.log(i); // logs 3, 5, 7
+}
+ +

Vòng lặp và log ra giá trị bên trong đối tượng iterable như một iterable object được khai báo để lặp, chính là các element bên trong mảng 3, 5, 7 và không bao gồm các property của object.

+ +

Đặc điểm

+ + + + + + + + + + + + + + + + + + + +
Đặc điểmStatusGhi chú
{{SpecName('ES2015', '#sec-for-in-and-for-of-statements', 'for...of statement')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-for-in-and-for-of-statements', 'for...of statement')}}{{Spec2('ESDraft')}}
+ +

Trình duyệt hổ trợ

+ + + +

{{Compat("javascript.statements.for_of")}}

+ +

Xem thêm

+ + diff --git a/files/vi/web/javascript/reference/statements/for/index.html b/files/vi/web/javascript/reference/statements/for/index.html new file mode 100644 index 0000000000..613732de85 --- /dev/null +++ b/files/vi/web/javascript/reference/statements/for/index.html @@ -0,0 +1,137 @@ +--- +title: for +slug: Web/JavaScript/Reference/Statements/for +translation_of: Web/JavaScript/Reference/Statements/for +--- +
{{jsSidebar("Statements")}}
+ +

The for statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually a block statement) to be executed in the loop.

+ +
{{EmbedInteractiveExample("pages/js/statement-for.html")}}
+ + + +

Syntax

+ +
for ([initialization]; [condition]; [final-expression])
+   statement
+ +
+
initialization
+
An expression (including assignment expressions) or variable declaration evaluated once before the loop begins. Typically used to initialize a counter variable. This expression may optionally declare new variables with var or let keywords. Variables declared with var are not local to the loop, i.e. they are in the same scope the for loop is in. Variables declared with let are local to the statement.
+
The result of this expression is discarded.
+
condition
+
An expression to be evaluated before each loop iteration. If this expression evaluates to true, statement is executed. This conditional test is optional. If omitted, the condition always evaluates to true. If the expression evaluates to false, execution skips to the first expression following the for construct.
+
final-expression
+
An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of condition. Generally used to update or increment the counter variable.
+
statement
+
A statement that is executed as long as the condition evaluates to true. To execute multiple statements within the loop, use a {{jsxref("Statements/block", "block", "", 0)}} statement ({ ... }) to group those statements. To execute no statement within the loop, use an {{jsxref("Statements/empty", "empty", "", 0)}} statement (;).
+
+ +

Examples

+ +

Using for

+ +

The following for statement starts by declaring the variable i and initializing it to 0. It checks that i is less than nine, performs the two succeeding statements, and increments i by 1 after each pass through the loop.

+ +
for (let i = 0; i < 9; i++) {
+   console.log(i);
+   // more statements
+}
+
+ +

Optional for expressions

+ +

All three expressions in the head of the for loop are optional.

+ +

For example, in the initialization block it is not required to initialize variables:

+ +
var i = 0;
+for (; i < 9; i++) {
+    console.log(i);
+    // more statements
+}
+
+ +

Like the initialization block, the condition block is also optional. If you are omitting this expression, you must make sure to break the loop in the body in order to not create an infinite loop.

+ +
for (let i = 0;; i++) {
+   console.log(i);
+   if (i > 3) break;
+   // more statements
+}
+ +

You can also omit all three blocks. Again, make sure to use a {{jsxref("Statements/break", "break")}} statement to end the loop and also modify (increase) a variable, so that the condition for the break statement is true at some point.

+ +
var i = 0;
+
+for (;;) {
+  if (i > 3) break;
+  console.log(i);
+  i++;
+}
+
+ +

Using for without a statement

+ +

The following for cycle calculates the offset position of a node in the final-expression section, and therefore it does not require the use of a statement section, a semicolon is used instead.

+ +
function showOffsetPos(sId) {
+
+  var nLeft = 0, nTop = 0;
+
+  for (
+
+    var oItNode = document.getElementById(sId); /* initialization */
+
+    oItNode; /* condition */
+
+    nLeft += oItNode.offsetLeft, nTop += oItNode.offsetTop, oItNode = oItNode.offsetParent /* final-expression */
+
+  ); /* semicolon */
+
+  console.log('Offset position of \'' + sId + '\' element:\n left: ' + nLeft + 'px;\n top: ' + nTop + 'px;');
+
+}
+
+/* Example call: */
+
+showOffsetPos('content');
+
+// Output:
+// "Offset position of "content" element:
+// left: 0px;
+// top: 153px;"
+ +
Note: This is one of the few cases in JavaScript where the semicolon is mandatory. Indeed, without the semicolon the line that follows the cycle declaration will be considered a statement.
+ +

Specifications

+ + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-for-statement', 'for statement')}}
+ +

Browser compatibility

+ + + +

{{Compat ("javascript.statements.for")}}

+ +

Xem thêm

+ + diff --git a/files/vi/web/javascript/reference/statements/function_star_/index.html b/files/vi/web/javascript/reference/statements/function_star_/index.html new file mode 100644 index 0000000000..388e0f8b34 --- /dev/null +++ b/files/vi/web/javascript/reference/statements/function_star_/index.html @@ -0,0 +1,208 @@ +--- +title: function* +slug: Web/JavaScript/Reference/Statements/function* +translation_of: Web/JavaScript/Reference/Statements/function* +--- +
{{jsSidebar("Statements")}}
+ +

Khai báo function* (từ khóa function tiếp theo là dấu sao) định nghĩa một generator function, một phương thức trả về đối tượng {{jsxref("Global_Objects/Generator","Generator")}}.

+ +
{{EmbedInteractiveExample("pages/js/statement-functionasterisk.html")}}
+ + + +
+

Bạn cũng có thể khai báo generator functions bằng constructor {{jsxref("GeneratorFunction")}} , hoặc cú pháp function expression.

+
+ +

Cú pháp

+ +
function* name([param[, param[, ... param]]]) {
+   statements
+}
+
+ +
+
name
+
Tên phương thức
+
+ +
+
param
+
Các tham số truyền vào cho phương thức.
+
+ +
+
statements
+
Các câu lệnh bên trong phương thức
+
+ +

Diễn giải

+ +

Generators là một hàm có thể thoát và sau đó gọi lại lần nữa. Giá trị của biến trong các lần gọi được lưu lại trong các lần gọi tiếp theo.
+
+ Pattern là cách hàm async được viết ra.

+ +

Gọi một generator function không thực thi các lệnh bên trong hàm ngày lập tức; Thay vào đó, một object iterator được trả về. Khi iterator gọi đến phương thức next() , lúc này các lệnh bên trong hàm được thực thi cho đến khi gặp câu {{jsxref("Operators/yield", "yield")}} , sau câu lệnh {{jsxref("Operators/yield", "yield")}} là giá trị sẽ trả về, hoặc gọi đến một generator function khác. Phương thức next() trả về một object với property value chứa giá trị yielded và property done , giá trị kiểu boolean, xác định generator yielded trả về đã là cuối cùng chưa. Gọi phương thức next() với một tham số sẽ chạy hàm generator tiếp tục, thay thế câu yield nơi hàm đã dừng lại trước đó với tham số từ next()

+ +

Câu lệnh return trong generator, khi chạy, sẽ kết thúc generator (ví dụ property done trả về sẽ có giá trị true). Nếu giá trị đã được trả về, nó sẽ được set cho property value.
+ Giống như câu lệnh return , thrown error trong generator sẽ kết thúc generator  -- trừ khi bắt lại bằng bên trong generator.
+ Khi một generator kết thúc, các câu gọi  next tiếp theo sau sẽ không được thực thi, nó chỉ trả về object có dạng: {value: undefined, done: true}.

+ +

Ví dụ

+ +

Ví dụ đơn giản

+ +
function* idMaker() {
+  var index = 0;
+  while (index < index+1)
+    yield index++;
+}
+
+var gen = idMaker();
+
+console.log(gen.next().value); // 0
+console.log(gen.next().value); // 1
+console.log(gen.next().value); // 2
+console.log(gen.next().value); // 3
+// ...
+ +

Ví dụ với yield*

+ +
function* anotherGenerator(i) {
+  yield i + 1;
+  yield i + 2;
+  yield i + 3;
+}
+
+function* generator(i) {
+  yield i;
+  yield* anotherGenerator(i);
+  yield i + 10;
+}
+
+var gen = generator(10);
+
+console.log(gen.next().value); // 10
+console.log(gen.next().value); // 11
+console.log(gen.next().value); // 12
+console.log(gen.next().value); // 13
+console.log(gen.next().value); // 20
+
+ +

Truyền tham số vào trong Generators

+ +
function* logGenerator() {
+  console.log(0);
+  console.log(1, yield);
+  console.log(2, yield);
+  console.log(3, yield);
+}
+
+var gen = logGenerator();
+
+gen.next();             // 0
+gen.next('pretzel');    // 1 pretzel
+gen.next('california'); // 2 california
+gen.next('mayonnaise'); // 3 mayonnaise
+
+ +

Return bên trong generator

+ +
function* yieldAndReturn() {
+  yield "Y";
+  return "R";
+  yield "unreachable";
+}
+
+var gen = yieldAndReturn()
+console.log(gen.next()); // { value: "Y", done: false }
+console.log(gen.next()); // { value: "R", done: true }
+console.log(gen.next()); // { value: undefined, done: true }
+
+ +

Generators không dùng constructable

+ +
function* f() {}
+var obj = new f; // throws "TypeError: f is not a constructor
+
+ +

Generator khai báo bằng expression

+ +
const foo = function* () {
+  yield 10;
+  yield 20;
+};
+
+const bar = foo();
+console.log(bar.next()); // {value: 10, done: false}
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES2015', '#sec-generator-function-definitions', 'function*')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ES2016', '#sec-generator-function-definitions', 'function*')}}{{Spec2('ES2016')}}Changed that generators should not have [[Construct]] trap and will throw when used with new.
{{SpecName('ESDraft', '#sec-generator-function-definitions', 'function*')}}{{Spec2('ESDraft')}}
+ +

Trình duyệt hỗ trợ

+ +
+ + +

{{Compat("javascript.statements.generator_function")}}

+
+ +

Lưu ý dành riêng cho Firefox

+ +

Generators và iterators trước phiên bản Firefox 26

+ +

Older Firefox versions implement an older version of the generators proposal. In the older version, generators were defined using a regular function keyword (without an asterisk) among other differences. See Legacy generator function for further information.

+ +

IteratorResult object returned instead of throwing

+ +

Starting with Gecko 29 {{geckoRelease(29)}}, the completed generator function no longer throws a {{jsxref("TypeError")}} "generator has already finished". Instead, it returns an IteratorResult object like { value: undefined, done: true } ({{bug(958951)}}).

+ +

Xem thêm

+ + diff --git a/files/vi/web/javascript/reference/statements/index.html b/files/vi/web/javascript/reference/statements/index.html new file mode 100644 index 0000000000..460884b7d9 --- /dev/null +++ b/files/vi/web/javascript/reference/statements/index.html @@ -0,0 +1,143 @@ +--- +title: Statements and declarations +slug: Web/JavaScript/Reference/Statements +tags: + - JavaScript + - NeedsTranslation + - Reference + - TopicStub + - statements +translation_of: Web/JavaScript/Reference/Statements +--- +
{{jsSidebar("Statements")}}
+ +

JavaScript applications consist of statements with an appropriate syntax. A single statement may span multiple lines. Multiple statements may occur on a single line if each statement is separated by a semicolon. This isn't a keyword, but a group of keywords.

+ +

Statements and declarations by category

+ +

For an alphabetical listing see the sidebar on the left.

+ +

Control flow

+ +
+
{{jsxref("Statements/block", "Block")}}
+
A block statement is used to group zero or more statements. The block is delimited by a pair of curly brackets.
+
{{jsxref("Statements/break", "break")}}
+
Terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.
+
{{jsxref("Statements/continue", "continue")}}
+
Terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.
+
{{jsxref("Statements/Empty", "Empty")}}
+
An empty statement is used to provide no statement, although the JavaScript syntax would expect one.
+
{{jsxref("Statements/if...else", "if...else")}}
+
Executes a statement if a specified condition is true. If the condition is false, another statement can be executed.
+
{{jsxref("Statements/switch", "switch")}}
+
Evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case.
+
{{jsxref("Statements/throw", "throw")}}
+
Throws a user-defined exception.
+
{{jsxref("Statements/try...catch", "try...catch")}}
+
Marks a block of statements to try, and specifies a response, should an exception be thrown.
+
+ +

Declarations

+ +
+
{{jsxref("Statements/var", "var")}}
+
Declares a variable, optionally initializing it to a value.
+
{{jsxref("Statements/let", "let")}}
+
Declares a block scope local variable, optionally initializing it to a value.
+
{{jsxref("Statements/const", "const")}}
+
Declares a read-only named constant.
+
+ +

Functions and classes

+ +
+
{{jsxref("Statements/function", "function")}}
+
Declares a function with the specified parameters.
+
{{jsxref("Statements/function*", "function*")}}
+
Generators functions enable writing iterators more easily.
+
{{jsxref("Statements/async_function", "async function")}}
+
Declares an async function with the specified parameters.
+
{{jsxref("Statements/return", "return")}}
+
Specifies the value to be returned by a function.
+
{{jsxref("Statements/class", "class")}}
+
Declares a class.
+
+ +

Iterations

+ +
+
{{jsxref("Statements/do...while", "do...while")}}
+
Creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.
+
{{jsxref("Statements/for", "for")}}
+
Creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement executed in the loop.
+
{{deprecated_inline}} {{non-standard_inline()}} {{jsxref("Statements/for_each...in", "for each...in")}}
+
Iterates a specified variable over all values of object's properties. For each distinct property, a specified statement is executed.
+
{{jsxref("Statements/for...in", "for...in")}}
+
Iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.
+
{{jsxref("Statements/for...of", "for...of")}}
+
Iterates over iterable objects (including {{jsxref("Global_Objects/Array","arrays","","true")}}, array-like objects, iterators and generators), invoking a custom iteration hook with statements to be executed for the value of each distinct property.
+
{{jsxref("Statements/while", "while")}}
+
Creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.
+
+ +

Others

+ +
+
{{jsxref("Statements/debugger", "debugger")}}
+
Invokes any available debugging functionality. If no debugging functionality is available, this statement has no effect.
+
{{jsxref("Statements/export", "export")}}
+
Used to export functions to make them available for imports in external modules, another scripts.
+
{{jsxref("Statements/import", "import")}}
+
Used to import functions exported from an external module, another script.
+
{{jsxref("Statements/label", "label")}}
+
Provides a statement with an identifier that you can refer to using a break or continue statement.
+
+ +
+
{{deprecated_inline}} {{jsxref("Statements/with", "with")}}
+
Extends the scope chain for a statement.
+
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES1', '#sec-12', 'Statements')}}{{Spec2('ES1')}}Initial definition
{{SpecName('ES3', '#sec-12', 'Statements')}}{{Spec2('ES3')}} 
{{SpecName('ES5.1', '#sec-12', 'Statements')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ES6')}}New: function*, let, for...of, yield, class
{{SpecName('ESDraft', '#sec-ecmascript-language-statements-and-declarations', 'ECMAScript Language: Statements and Declarations')}}{{Spec2('ESDraft')}} 
+ +

See also

+ + diff --git a/files/vi/web/javascript/reference/statements/throw/index.html b/files/vi/web/javascript/reference/statements/throw/index.html new file mode 100644 index 0000000000..c3116c8847 --- /dev/null +++ b/files/vi/web/javascript/reference/statements/throw/index.html @@ -0,0 +1,193 @@ +--- +title: throw +slug: Web/JavaScript/Reference/Statements/throw +translation_of: Web/JavaScript/Reference/Statements/throw +--- +
{{jsSidebar("Statements")}}
+ +

Câu lệnh throw  sẽ đưa ra một exception theo cách chúng ta định nghĩa. Các câu lệnh phía sau throw sẽ không được chạy, và sẽ gọi hàm callback catch đầu tiên tìm thấy. Nếu không có hàm catch, chương trình sẽ không chạy nữa.

+ +
{{EmbedInteractiveExample("pages/js/statement-throw.html")}}
+ + + +

Cú pháp

+ +
throw expression; 
+ +
+
expression
+
Một diễn giải.
+
+ +

Giải thích

+ +

Sử dụng câu lệnh throw để đưa ra một exception. Giá trị của expression trả về có thể string, number, boolean, hay Object. Mỗi câu throw chỉ trả về một exception

+ +
throw 'Error2'; // 1 exception dạng string
+throw 42;       // 1 exception giá trị 42
+throw true;     // 1 exception với giá trị boolean là true
+throw new Error('Required');  // tạo một error object với nội dung Required
+
+ +

Câu lệnh throw tuân thủ nguyên tắc automatic semicolon insertion (ASI) ,  nghĩa là không được phép xuống dòng giữa từ khóa throw và expression.

+ +

Ví dụ

+ +

Throw một object

+ +

Exception có thể là một object. Lúc này có thể tham chiếu đến các property của object bên trong khối lệnh catch . Ví dụ sau, tạo một object với kiểu là UserException và sử dụng nó trong câu throw.

+ +
function UserException(message) {
+   this.message = message;
+   this.name = 'UserException';
+}
+function getMonthName(mo) {
+   mo = mo - 1; // Thay đổi giá trị của index array tương ứng cho tháng (1 = Jan, 12 = Dec)
+   var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
+      'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
+   if (months[mo] !== undefined) {
+      return months[mo];
+   } else {
+      throw new UserException('InvalidMonthNo');
+   }
+}
+
+try {
+   // statements to try
+   var myMonth = 15; // 15 nằm ngoài giá trị cho phép
+   var monthName = getMonthName(myMonth);
+} catch (e) {
+   monthName = 'unknown';
+   console.log(e.message, e.name); // truyền exception object vào câu lệnh xử lý nếu có lỗi
+}
+
+ +

Một ví dụ khác sử dụng  object

+ +

Trong ví dụ sau, kiểm tra input, chỉ cho phép là giá trị U.S. zip code. Nếu giá trị zip code này không đúng format, throw một exception object là ZipCodeFormatException.

+ +
/*
+ * Creates a ZipCode object.
+ *
+ * Accepted formats for a zip code are:
+ *    12345
+ *    12345-6789
+ *    123456789
+ *    12345 6789
+ *
+ * If the argument passed to the ZipCode constructor does not
+ * conform to one of these patterns, an exception is thrown.
+ */
+
+function ZipCode(zip) {
+   zip = new String(zip);
+   pattern = /[0-9]{5}([- ]?[0-9]{4})?/;
+   if (pattern.test(zip)) {
+      // giá trị zip code value sẽ là giá trị đầu tiên khớp trong string
+      this.value = zip.match(pattern)[0];
+      this.valueOf = function() {
+         return this.value
+      };
+      this.toString = function() {
+         return String(this.value)
+      };
+   } else {
+      throw new ZipCodeFormatException(zip);
+   }
+}
+
+function ZipCodeFormatException(value) {
+   this.value = value;
+   this.message = 'does not conform to the expected format for a zip code';
+   this.toString = function() {
+      return this.value + this.message;
+   };
+}
+
+/*
+ * Đoạn script validate address theo kiểu US addresses.
+ */
+
+const ZIPCODE_INVALID = -1;
+const ZIPCODE_UNKNOWN_ERROR = -2;
+
+function verifyZipCode(z) {
+   try {
+      z = new ZipCode(z);
+   } catch (e) {
+      if (e instanceof ZipCodeFormatException) {
+         return ZIPCODE_INVALID;
+      } else {
+         return ZIPCODE_UNKNOWN_ERROR;
+      }
+   }
+   return z;
+}
+
+a = verifyZipCode(95060);         // returns 95060
+b = verifyZipCode(9560);          // returns -1
+c = verifyZipCode('a');           // returns -1
+d = verifyZipCode('95060');       // returns 95060
+e = verifyZipCode('95060 1234');  // returns 95060 1234
+
+ +

Rethrow một exception

+ +

Chúng ta có thể sử dụng throw để rethrow một exception sau khi đã catch nó. Trong ví dụ sau, catch lại exception nếu là giá trị lớn hơn 50 thì rethrow. Exception này sẽ được đưa lên hàm trên một cấp hoặc lên trên cùng cho các hàm catch khác.

+ +
try {
+   throw n; // throws một exception với giá trị là số
+} catch (e) {
+   if (e <= 50) {
+      // câu lệnh xử lý cho exception từ 1-50
+   } else {
+      // không có xử lý cho trường hợp exception này, rethrow
+      throw e;
+   }
+}
+
+ +

Specification

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Khởi tạo. Hiện thực trong JavaScript 1.4
{{SpecName('ES5.1', '#sec-12.13', 'throw statement')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-throw-statement', 'throw statement')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-throw-statement', 'throw statement')}}{{Spec2('ESDraft')}} 
+ +

Trình duyệt hổ trợ

+ + + +

{{Compat("javascript.statements.throw")}}

+ +

Xem thêm

+ + -- cgit v1.2.3-54-g00ecf