From 95aca4b4d8fa62815d4bd412fff1a364f842814a Mon Sep 17 00:00:00 2001 From: Ryan Johnson Date: Thu, 29 Apr 2021 16:16:42 -0700 Subject: remove retired locales (#699) --- .../reference/classes/constructor/index.html | 127 ---- .../reference/classes/extends/index.html | 108 ---- .../vi/web/javascript/reference/classes/index.html | 410 ------------- .../vi/web/javascript/reference/errors/index.html | 31 - .../missing_semicolon_before_statement/index.html | 67 --- .../errors/more_arguments_needed/index.html | 45 -- .../reference/errors/not_a_function/index.html | 84 --- .../reference/errors/too_much_recursion/index.html | 55 -- .../reference/functions/arguments/index.html | 234 -------- .../reference/functions/arrow_functions/index.html | 426 ------------- .../functions/default_parameters/index.html | 198 ------- .../web/javascript/reference/functions/index.html | 657 --------------------- .../global_objects/array/concat/index.html | 150 ----- .../global_objects/array/copywithin/index.html | 170 ------ .../global_objects/array/entries/index.html | 82 --- .../global_objects/array/every/index.html | 236 -------- .../reference/global_objects/array/fill/index.html | 149 ----- .../global_objects/array/filter/index.html | 232 -------- .../reference/global_objects/array/find/index.html | 226 ------- .../global_objects/array/findindex/index.html | 207 ------- .../reference/global_objects/array/flat/index.html | 179 ------ .../global_objects/array/foreach/index.html | 303 ---------- .../reference/global_objects/array/from/index.html | 228 ------- .../global_objects/array/includes/index.html | 135 ----- .../reference/global_objects/array/index.html | 433 -------------- .../global_objects/array/indexof/index.html | 228 ------- .../global_objects/array/isarray/index.html | 130 ---- .../reference/global_objects/array/join/index.html | 113 ---- .../reference/global_objects/array/map/index.html | 316 ---------- .../reference/global_objects/array/of/index.html | 92 --- .../reference/global_objects/array/pop/index.html | 96 --- .../reference/global_objects/array/push/index.html | 136 ----- .../global_objects/array/reduce/index.html | 553 ----------------- .../global_objects/array/reduceright/index.html | 347 ----------- .../global_objects/array/reverse/index.html | 124 ---- .../global_objects/array/shift/index.html | 141 ----- .../global_objects/array/slice/index.html | 249 -------- .../reference/global_objects/array/some/index.html | 206 ------- .../reference/global_objects/array/sort/index.html | 248 -------- .../global_objects/array/splice/index.html | 161 ----- .../global_objects/array/tolocalestring/index.html | 167 ------ .../global_objects/array/tostring/index.html | 75 --- .../global_objects/array/unshift/index.html | 119 ---- .../global_objects/array/values/index.html | 113 ---- .../global_objects/arraybuffer/index.html | 141 ----- .../reference/global_objects/date/index.html | 260 -------- .../reference/global_objects/date/parse/index.html | 202 ------- .../reference/global_objects/error/index.html | 241 -------- .../global_objects/function/call/index.html | 148 ----- .../reference/global_objects/function/index.html | 150 ----- .../global_objects/function/tosource/index.html | 65 -- .../reference/global_objects/generator/index.html | 130 ---- .../javascript/reference/global_objects/index.html | 203 ------- .../reference/global_objects/infinity/index.html | 81 --- .../reference/global_objects/isfinite/index.html | 97 --- .../reference/global_objects/json/index.html | 132 ----- .../reference/global_objects/map/index.html | 263 --------- .../reference/global_objects/math/abs/index.html | 108 ---- .../reference/global_objects/math/ceil/index.html | 172 ------ .../reference/global_objects/math/floor/index.html | 132 ----- .../reference/global_objects/math/index.html | 196 ------ .../reference/global_objects/math/sqrt/index.html | 101 ---- .../reference/global_objects/nan/index.html | 97 --- .../reference/global_objects/number/index.html | 216 ------- .../global_objects/number/isfinite/index.html | 88 --- .../global_objects/number/isinteger/index.html | 88 --- .../global_objects/number/isnan/index.html | 99 ---- .../global_objects/number/issafeinteger/index.html | 94 --- .../number/max_safe_integer/index.html | 71 --- .../number/min_safe_integer/index.html | 61 -- .../reference/global_objects/number/nan/index.html | 63 -- .../number/negative_infinity/index.html | 96 --- .../number/positive_infinity/index.html | 96 --- .../global_objects/object/assign/index.html | 259 -------- .../object/defineproperties/index.html | 228 ------- .../object/defineproperty/index.html | 483 --------------- .../object/getownpropertynames/index.html | 156 ----- .../reference/global_objects/object/index.html | 213 ------- .../global_objects/object/tostring/index.html | 128 ---- .../global_objects/object/valueof/index.html | 108 ---- .../global_objects/promise/all/index.html | 121 ---- .../global_objects/promise/catch/index.html | 136 ----- .../global_objects/promise/finally/index.html | 95 --- .../reference/global_objects/promise/index.html | 317 ---------- .../global_objects/regexp/exec/index.html | 194 ------ .../reference/global_objects/regexp/index.html | 618 ------------------- .../reference/global_objects/string/index.html | 405 ------------- .../global_objects/string/match/index.html | 160 ----- .../global_objects/string/normalize/index.html | 146 ----- .../global_objects/string/repeat/index.html | 118 ---- .../global_objects/string/replace/index.html | 233 -------- .../global_objects/string/slice/index.html | 138 ----- .../global_objects/string/startswith/index.html | 128 ---- .../global_objects/string/substr/index.html | 121 ---- .../global_objects/string/substring/index.html | 195 ------ .../reference/global_objects/weakmap/index.html | 138 ----- files/vi/web/javascript/reference/index.html | 50 -- .../reference/iteration_protocols/index.html | 383 ------------ .../operators/conditional_operator/index.html | 119 ---- .../reference/operators/delete/index.html | 292 --------- .../reference/operators/function/index.html | 175 ------ .../web/javascript/reference/operators/index.html | 298 ---------- .../operators/operator_precedence/index.html | 477 --------------- .../reference/operators/super/index.html | 226 ------- .../javascript/reference/operators/this/index.html | 382 ------------ .../reference/operators/typeof/index.html | 271 --------- .../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 ------ .../reference/template_literals/index.html | 238 -------- 116 files changed, 22099 deletions(-) delete mode 100644 files/vi/web/javascript/reference/classes/constructor/index.html delete mode 100644 files/vi/web/javascript/reference/classes/extends/index.html delete mode 100644 files/vi/web/javascript/reference/classes/index.html delete mode 100644 files/vi/web/javascript/reference/errors/index.html delete mode 100644 files/vi/web/javascript/reference/errors/missing_semicolon_before_statement/index.html delete mode 100644 files/vi/web/javascript/reference/errors/more_arguments_needed/index.html delete mode 100644 files/vi/web/javascript/reference/errors/not_a_function/index.html delete mode 100644 files/vi/web/javascript/reference/errors/too_much_recursion/index.html delete mode 100644 files/vi/web/javascript/reference/functions/arguments/index.html delete mode 100644 files/vi/web/javascript/reference/functions/arrow_functions/index.html delete mode 100644 files/vi/web/javascript/reference/functions/default_parameters/index.html delete mode 100644 files/vi/web/javascript/reference/functions/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/concat/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/copywithin/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/entries/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/every/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/fill/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/filter/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/find/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/findindex/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/flat/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/foreach/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/from/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/includes/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/indexof/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/isarray/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/join/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/map/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/of/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/pop/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/push/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/reduce/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/reduceright/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/reverse/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/shift/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/slice/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/some/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/sort/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/splice/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/tolocalestring/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/tostring/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/unshift/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/array/values/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/arraybuffer/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/date/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/date/parse/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/error/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/function/call/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/function/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/function/tosource/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/generator/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/infinity/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/isfinite/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/json/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/map/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/math/abs/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/math/ceil/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/math/floor/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/math/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/math/sqrt/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/nan/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/number/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/number/isfinite/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/number/isinteger/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/number/isnan/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/number/issafeinteger/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/number/max_safe_integer/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/number/min_safe_integer/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/number/nan/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/number/negative_infinity/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/number/positive_infinity/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/object/assign/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/object/defineproperties/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/object/defineproperty/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/object/getownpropertynames/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/object/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/object/tostring/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/object/valueof/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/promise/all/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/promise/catch/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/promise/finally/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/promise/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/regexp/exec/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/regexp/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/string/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/string/match/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/string/normalize/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/string/repeat/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/string/replace/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/string/slice/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/string/startswith/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/string/substr/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/string/substring/index.html delete mode 100644 files/vi/web/javascript/reference/global_objects/weakmap/index.html delete mode 100644 files/vi/web/javascript/reference/index.html delete mode 100644 files/vi/web/javascript/reference/iteration_protocols/index.html delete mode 100644 files/vi/web/javascript/reference/operators/conditional_operator/index.html delete mode 100644 files/vi/web/javascript/reference/operators/delete/index.html delete mode 100644 files/vi/web/javascript/reference/operators/function/index.html delete mode 100644 files/vi/web/javascript/reference/operators/index.html delete mode 100644 files/vi/web/javascript/reference/operators/operator_precedence/index.html delete mode 100644 files/vi/web/javascript/reference/operators/super/index.html delete mode 100644 files/vi/web/javascript/reference/operators/this/index.html delete mode 100644 files/vi/web/javascript/reference/operators/typeof/index.html delete mode 100644 files/vi/web/javascript/reference/statements/async_function/index.html delete mode 100644 files/vi/web/javascript/reference/statements/continue/index.html delete mode 100644 files/vi/web/javascript/reference/statements/do...while/index.html delete mode 100644 files/vi/web/javascript/reference/statements/export/index.html delete mode 100644 files/vi/web/javascript/reference/statements/for...of/index.html delete mode 100644 files/vi/web/javascript/reference/statements/for/index.html delete mode 100644 files/vi/web/javascript/reference/statements/function_star_/index.html delete mode 100644 files/vi/web/javascript/reference/statements/index.html delete mode 100644 files/vi/web/javascript/reference/statements/throw/index.html delete mode 100644 files/vi/web/javascript/reference/template_literals/index.html (limited to 'files/vi/web/javascript/reference') diff --git a/files/vi/web/javascript/reference/classes/constructor/index.html b/files/vi/web/javascript/reference/classes/constructor/index.html deleted file mode 100644 index dddb2555f3..0000000000 --- a/files/vi/web/javascript/reference/classes/constructor/index.html +++ /dev/null @@ -1,127 +0,0 @@ ---- -title: constructor -slug: Web/JavaScript/Reference/Classes/constructor -translation_of: Web/JavaScript/Reference/Classes/constructor ---- -
{{jsSidebar("Classes")}}
- -

Phương thức constructor là một phương thức đặc biệt dùng để khởi tạo 1 object và được tạo ở trong class.

- -
{{EmbedInteractiveExample("pages/js/classes-constructor.html")}}
- - - -

Cú pháp

- -
constructor([arguments]) { ... }
- -

Mô tả

- -

Chỉ có duy nhất 1 phương thức đặc biệt tên là "constructor" ở trong class. Có nhiều hơn 1 phương thức constructor ở trong class thì sẽ gây ra lỗi{{jsxref("SyntaxError")}}.

- -

Một constructor có thể sử dụng từ khóa {{jsxref("Operators/super", "super")}} để gọi đến constructor của class cha.

- -

Nếu bạn không chỉ định 1 phương thức constructor thì constructor mặc định sẽ được sử dụng

- -

Ví dụ

- -

Sử dụng phương thức constructor 

- -

Đoạn code này được lấy từ classes sample (live demo).

- -
class Square extends Polygon {
-  constructor(length) {
-    // Here, it calls the parent class' constructor with lengths
-    // provided for the Polygon's width and height
-    super(length, length);
-    // Note: In derived classes, super() must be called before you
-    // can use 'this'. Leaving this out will cause a reference error.
-    this.name = 'Square';
-  }
-
-  get area() {
-    return this.height * this.width;
-  }
-
-  set area(value) {
-    this.area = value;
-  }
-}
- -

Ví dụ khác

- -

Hãy xem đoạn code sau

- -
class Polygon {
-    constructor() {
-        this.name = "Polygon";
-    }
-}
-
-class Square extends Polygon {
-    constructor() {
-        super();
-    }
-}
-
-class Rectangle {}
-
-Object.setPrototypeOf(Square.prototype, Rectangle.prototype);
-
-console.log(Object.getPrototypeOf(Square.prototype) === Polygon.prototype); //false
-console.log(Object.getPrototypeOf(Square.prototype) === Rectangle.prototype); //true
-
-let newInstance = new Square();
-console.log(newInstance.name); //Polygon
- -

Ở đây prototype của class Square đã bị thay đổi nhưng constructor kế thừa từ class Polygon vẫn được gọi khi tạo ra 1 thực thể mới.

- -

Default constructors

- -

Như đã nói ởi trước, nếu bạn không chỉ đỉnh 1 phương thức constructor thì default constructor sẽ được sử dụng. Với những class cơ bản thì default contructor sẽ là:

- -
constructor() {}
-
- -

Với những class dẫn xuất, default constructor sẽ là:

- -
constructor(...args) {
-  super(...args);
-}
- -

Thông số kĩ thuật

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-static-semantics-constructormethod', 'Constructor Method')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-static-semantics-constructormethod', 'Constructor Method')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- - - -

{{Compat("javascript.classes.constructor")}}

- -

Bài viết liên quan

- - diff --git a/files/vi/web/javascript/reference/classes/extends/index.html b/files/vi/web/javascript/reference/classes/extends/index.html deleted file mode 100644 index a7a2438965..0000000000 --- a/files/vi/web/javascript/reference/classes/extends/index.html +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: extends(Thừa kế) -slug: Web/JavaScript/Reference/Classes/extends -translation_of: Web/JavaScript/Reference/Classes/extends ---- -
{{jsSidebar("Classes")}}
- -

Từ khóa extends được sử dụng trong khai báo class hoặc trong class expressions để tạo ra 1 class con là con của class khác

- -
{{EmbedInteractiveExample("pages/js/classes-extends.html", "taller")}}
- - - -

Cú pháp

- -
class ChildClass extends ParentClass { ... }
- -

Mô tả

- -

Từ khó extends có thể được sử dụng để tạo ra class con từ những class mà chúng ta tạo ra hoặc những class sẵn có

- -

Thuộc tính .prototype của lớp được kế thừa phải trả về giá trị là  {{jsxref("Object")}} hoặc {{jsxref("null")}}.

- -

Ví dụ

- -

Sử dụng extends

- -

Ở ví dụ đầu tiên tạo ra 1 class Square từ class Polygon. Ví dụ này được lấy từ  đây (source).

- -
class Square extends Polygon {
-  constructor(length) {
-    // Ở đây, gọi 1 constructor từ class cha với tham số truyền vào là length
-    // cung cấp chiều rộng vào chiều cao của class Polygon
-    super(length, length);
-    // Chú ý: trong những class con, super()  phải được gọi trước khi
-    // bạn có thể sử dụng từ khóa 'this'. Nếu không sẽ gây ra lỗi tham chiếu
-    this.name = 'Square';
-  }
-
-  get area() {
-    return this.height * this.width;
-  }
-}
- -

Sử dụng extends với những object có sẵn

- -

Trong ví dụ này chúng ta thừa kế từ object có sẵn là {{jsxref("Date")}} . Ví dụ này được lấy từ đây(source).

- -
class myDate extends Date {
-  constructor() {
-    super();
-  }
-
-  getFormattedDate() {
-    var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
-    return this.getDate() + '-' + months[this.getMonth()] + '-' + this.getFullYear();
-  }
-}
- -

Thừa kế từ null

- -

Thừa kế từ {{jsxref("null")}} cũng giống như class thông thường, ngoại trừ rằng các prototype của object sẽ không được thừa kế từ {{jsxref("Object.prototype")}}.

- -
class nullExtends extends null {
-  constructor() {}
-}
-
-Object.getPrototypeOf(nullExtends); // Function.prototype
-Object.getPrototypeOf(nullExtends.prototype) // null
-
-new nullExtends(); //ReferenceError: this is not defined
-
- -

Thông số kĩ thuật

- - - - - - - - - - - - - - - - - - - -
Thông sốTrạng tháiBình luận
{{SpecName('ES2015', '#sec-class-definitions', 'extends')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-class-definitions', 'extends')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt tương thích

- - - -

{{Compat("javascript.classes.extends")}}

- -

Bài viết liên quan

- - diff --git a/files/vi/web/javascript/reference/classes/index.html b/files/vi/web/javascript/reference/classes/index.html deleted file mode 100644 index 02a693e6fc..0000000000 --- a/files/vi/web/javascript/reference/classes/index.html +++ /dev/null @@ -1,410 +0,0 @@ ---- -title: Classes -slug: Web/JavaScript/Reference/Classes -tags: - - Class trong ES6 - - JavaScript - - biểu thức class - - class declarations - - class expressions - - class trong javasript - - khai báo class - - thừa kế -translation_of: Web/JavaScript/Reference/Classes ---- -
{{JsSidebar("Classes")}}
- -
Lớp (class) trong JavaScript được giới thiệu trong ECMAScript 2015 chủ yếu là cú pháp cải tiến (syntactical sugar) dựa trên nền tảng thừa kế nguyên mẫu (prototypal inheritance) sẵn có trong JavaScript. Cú pháp class không giới thiệu mô hình thừa kế hướng đối tượng mới cho JavaScript.
- -

Định nghĩa class

- -

Thực tế các class giống như các "function đặc biệt", và cũng giống như bạn có thể định nghĩa hàm biểu thức (function expressions)  và khai báo hàm (function declarations), cú pháp class có hai thành phần: biểu thức class (class expressions) và khai báo class (class declarations).

- -

Khai báo class

- -

Một cách để định nghĩa class là sử dụng khai báo lớp class declaration. Để khai báo một class, bạn sử dụng từ khóa class  với tên của class đằng sau (ví dụ "Rectangle" như dưới đây).

- -
class Rectangle {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-}
- -

Hoisting (sự kéo lên)

- -

Một sự khác biệt quan trọng giữa khai báo hàmkhai báo class mà các bạn cần chú ý đó là khai báo hàm được kéo lên đầu ({{Glossary("Hoisting", "hoisted")}}), và khai báo class thì không. Bạn cần khai báo class của bạn trước tiên sau đó mới có thể gọi và sử dụng nó, ngược lại nếu viết code giống như phía dưới đây thì sẽ xảy ra lỗi {{jsxref("ReferenceError")}}:

- -
var p = new Rectangle(); // ReferenceError
-
-class Rectangle {}
-
- -

Biểu thức class

- -

Một biểu thức class là một cách khác để khai báo một class. Biểu thức class có thể có tên hoặc không tên. Biểu thức class nếu có tên, thì tên đó chỉ được nhìn thấy bên trong thân class. (Tuy nhiên từ bên ngoài nó có thể được lấy ra thông qua thuộc tính {{jsxref("Function.name", "name")}} của class (không phải instance)).

- -
// biểu thức class không tên
-var Rectangle = class {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-};
-
-console.log(Rectangle.name);
-// output: "Rectangle" (tên của biến được gán)
-
-// biểu thức class có tên
-var Rectangle = class Rectangle2 {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-};
-
-console.log(Rectangle.name);
-// output: "Rectangle2" (tên phía sau từ khóa class)
-
- -
-

Lưu ý: Các biểu thức class cũng theo quy luật hoisting như của {{anch("Class declarations")}} đề cập ở trên.

-
- -

Thân class và định nghĩa phương thức

- -

Phần thân của một class là phần nằm trong dấu ngoặc nhọn {}. Tại đó bạn có thể định nghĩa các thành phần của class như phương thức (method) hoặc hàm khởi tạo (constructor).

- -

Strict mode

- -

Các phần tử khai báo trong class declarations và class expressions đã được thực hiện ở chế độ strict mode như constructor, static tương tự đối với prototype methods, setter, getter functions. (Nếu bạn chưa hiểu chế độ strict mode thì hãy tìm hiểu thêm tại đây).

- -

Constructor (hàm khởi tạo)

- -

Hàm khởi tạo (constructor) là một hàm đặc biệt, nhiệm vụ của nó là khởi tạo một đối tượng cho một class. Trong một class chỉ có thể tồn tại duy nhất một hàm khởi tạo, nghĩa là bạn chỉ có thể khai báo duy nhất một hàm với tên "constructor". Nếu bạn cố gắng làm ngược lại (khai báo nhiều hơn một hàm constructor) thì sẽ xuất hiện lỗi {{jsxref("SyntaxError")}}.

- -

Một constructor có thể sử dụng từ khóa super để gọi tới hàm constructor của class cha.

- -

Phương thức Prototype

- -

Xem thêm định nghĩa hàm.

- -
class Rectangle {
-  constructor(height, width) {
-    this.height = height;
-    this.width = width;
-  }
-
-  get area() {
-    return this.calcArea();
-  }
-
-  calcArea() {
-    return this.height * this.width;
-  }
-}
-
-const square = new Rectangle(10, 10);
-
-console.log(square.area);
- -

Phương thức Static (phương thức tĩnh)

- -

Từ khóa static định nghĩa một hàm static (hàm tĩnh) trong một class. Nếu muốn gọi hàm static này thì bạn không cần gọi chúng thông qua các instantiating của class đó và bạn cũng không thể gọi chúng thông qua cách khởi tạo class. Hàm static thường được sử dụng vào mục đích tạo ra một hàm tiện ích (có thể gọi là hàm dùng chung) cho cả một ứng dụng.

- -
class Point {
-  constructor(x, y) {
-    this.x = x;
-    this.y = y;
-  }
-
-  static distance(a, b) {
-    const dx = a.x - b.x;
-    const dy = a.y - b.y;
-
-    return Math.hypot(dx, dy);
-  }
-}
-
-const p1 = new Point(5, 5);
-const p2 = new Point(10, 10);
-
-console.log(Point.distance(p1, p2));
- -

Boxing với phương thức prototype và static

- -

Khi hai hàm static và prototype được gọi trực tiếp (không cần tạo đối tượng có giá trị "this") thì bây giờ bên trong hàm gọi, giá trị this sẽ là undefine. Autoboxing sẽ không xảy ra. Hành vi này sẽ giống nhau ngay cả khi chúng ta viết code ở strict mode bởi vì tất cả các hàm, phương thức, hàm khởi tạo, setter và getter đều thực thi mặc định ở strict mode. Chính vì vậy nếu chúng ta không chỉ định giá trị "this" thì giá trị của "this" sẽ là undefined.

- -
class Animal {
-  speak() {
-    return this;
-  }
-  static eat() {
-    return this;
-  }
-}
-
-let obj = new Animal();
-obj.speak(); // Animal {}
-let speak = obj.speak;
-speak(); // undefined
-
-Animal.eat() // class Animal
-let eat = Animal.eat;
-eat(); // undefined
-
- -

Nếu chúng ta chỉnh sửa code như trên bằng cách sửa dụng prototype thì autoboxing sẽ tự động hiểu rằng giá trị this bấy giờ là dựa trên cái hàm được gọi. Tham khảo code bên dưới.

- -
function Animal() { }
-
-Animal.prototype.speak = function() {
-  return this;
-}
-
-Animal.eat = function() {
-  return this;
-}
-
-let obj = new Animal();
-let speak = obj.speak;
-speak(); // global object
-
-let eat = Animal.eat;
-eat(); // global object
-
- -

Tạo lớp con với extends

- -

Từ khóa extends được sử dụng trong class declarations hoặc class expressions để tạo ra một class con kế thừa từ một class sẵn có (class cha).

- -
class Animal {
-  constructor(name) {
-    this.name = name;
-  }
-
-  speak() {
-    console.log(this.name + ' makes a noise.');
-  }
-}
-
-class Dog extends Animal {
-  speak() {
-    console.log(this.name + ' barks.');
-  }
-}
-
-var d = new Dog('Mitzie');
-d.speak(); // Mitzie barks.
-
- -

Nếu có một constructor trong lớp con (sub-class), nó cần gọi hàm super() trước khi có thể sử dụng "this".

- -

Một cách khác cũng có thể gọi và mở rộng hàm có sẵn là dùng prototype:

- -
function Animal (name) {
-  this.name = name;
-}
-
-Animal.prototype.speak = function () {
-  console.log(this.name + ' makes a noise.');
-}
-
-class Dog extends Animal {
-  speak() {
-    console.log(this.name + ' barks.');
-  }
-}
-
-var d = new Dog('Mitzie');
-d.speak(); // Mitzie barks.
-
- -

Cần lưu ý rằng các class không thể extend một object bình thường trong javascript (regular object). Do đó nếu bạn muốn kế thừa một hàm từ object bình thường này, bạn cần thay thế và sử dụng {{jsxref("Object.setPrototypeOf()")}}:

- -
var Animal = { // regular object
-  speak() {
-    console.log(this.name + ' makes a noise.');
-  }
-};
-
-class Dog { //
-  constructor(name) {
-    this.name = name;
-  }
-}
-
-Object.setPrototypeOf(Dog.prototype, Animal);// Nếu bạn không làm điều này khi gọi hàm speak thì sẽ sinh ra lỗi
-
-var d = new Dog('Mitzie'); // đối tượng của class Dog
-d.speak(); // Mitzie makes a noise.
-
- -

Species

- -

Bạn có thể muốn trả về các đối tượng {{jsxref("Array")}} trong mảng của class MyArray. Mô hình species sẽ cho phép bạn ghi đè lên các hàm khởi tạo mặc định.

- -

Ví dụ, khi sử dụng những phương thức như là {{jsxref("Array.map", "map()")}} điều đó sẽ trả về giá trị khởi tạo mặc định, bạn muốn những phương thức đó trả về một mảng đối tượng của Array, thay vì đối tượng của MyArray. {{jsxref("Symbol.species")}}  sẽ cho phép bạn thực hiện điều này:

- -
class MyArray extends Array {
-  // Overwrite species to the parent Array constructor
-  static get [Symbol.species]() { return Array; }
-}
-
-var a = new MyArray(1,2,3);
-var mapped = a.map(x => x * x);
-
-console.log(mapped instanceof MyArray); // false
-console.log(mapped instanceof Array);   // true
-
- -

Gọi class cha sử dụng super

- -

Từ khóa super dùng để gọi một hàm có sẵn ở đối tượng cha.

- -
class Cat {
-  constructor(name) {
-    this.name = name;
-  }
-
-  speak() {
-    console.log(this.name + ' makes a noise.');
-  }
-}
-
-class Lion extends Cat {
-  speak() {
-    super.speak();
-    console.log(this.name + ' roars.');
-  }
-}
-
-var l = new Lion('Fuzzy');
-l.speak();
-// Fuzzy makes a noise.
-// Fuzzy roars.
-
-
- -

Mix-ins

- -

Abstract subclasses or mix-ins are templates for classes. An ECMAScript class can only have a single superclass, so multiple inheritance from tooling classes, for example, is not possible. The functionality must be provided by the superclass.

- -

A function with a superclass as input and a subclass extending that superclass as output can be used to implement mix-ins in ECMAScript:

- -

Tập hợp các class con hoặc mix-ins được gọi là khuôn mẫu cho các class. Trong ECMAScript một class chỉ có thể có một lớp cha, vì vậy để thừa kế từ tập hợp các class (kế thừa nhiều class) là điều không thể. Các chức năng phải được cung cấp bởi lớp mà nó kế thừa (cung cấp bởi lớp cha).

- -

Một hàm mà đã được định nghĩa ở lớp cha và lớp con muốn kế thừa và mở rộng hàm đó ra thì có thể sự dụng các lệnh mix-ins trong  ECMAScript như sau:

- -
var calculatorMixin = Base => class extends Base {
-  calc() { }
-};
-
-var randomizerMixin = Base => class extends Base {
-  randomize() { }
-};
-
- -

Một class để sử dụng mix-ins này có thể viết code như thế này:

- -
class Foo { }
-class Bar extends calculatorMixin(randomizerMixin(Foo)) { }
- -

Đặc điểm kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ES2016', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2016')}}
{{SpecName('ES2017', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ES2017')}}
{{SpecName('ESDraft', '#sec-class-definitions', 'Class definitions')}}{{Spec2('ESDraft')}}
- -

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

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)EdgeInternet ExplorerOperaSafari
Basic support{{CompatChrome(42.0)}}[1]
- {{CompatChrome(49.0)}}
{{CompatGeckoDesktop(45)}}13{{CompatNo}}{{CompatOpera(43.0)}}{{CompatSafari(9.0)}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatVersionUnknown}}{{CompatGeckoMobile(45)}}{{CompatUnknown}}{{CompatUnknown}}9{{CompatChrome(56.0)}}
-
- -

[1] Yêu cầu chế độ strict (luôn chạy javascript ở chế độ này). Tắt strict mode trong flag "Enable Experimental JavaScript", mặc định flag này bị vô hiệu hóa.

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/errors/index.html b/files/vi/web/javascript/reference/errors/index.html deleted file mode 100644 index c295fccea6..0000000000 --- a/files/vi/web/javascript/reference/errors/index.html +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: JavaScript error reference -slug: Web/JavaScript/Reference/Errors -tags: - - Debugging - - Error - - Errors - - Exception - - JavaScript - - NeedsTranslation - - TopicStub - - exceptions -translation_of: Web/JavaScript/Reference/Errors ---- -

{{jsSidebar("Errors")}}

- -

Below, you'll find a list of errors which are thrown by JavaScript. These errors can be a helpful debugging aid, but the reported problem isn't always immediately clear. The pages below will provide additional details about these errors. Each error is an object based upon the {{jsxref("Error")}} object, and has a name and a message.

- -

Errors displayed in the Web console may include a link to the corresponding page below to help you quickly comprehend the problem in your code.

- -

List of errors

- -

In this list, each page is listed by name (the type of error) and message (a more detailed human-readable error message). Together, these two properties provide a starting point toward understanding and resolving the error. For more information, follow the links below!

- -

{{ListSubPages("/en-US/docs/Web/JavaScript/Reference/Errors")}}

- -

See also

- - diff --git a/files/vi/web/javascript/reference/errors/missing_semicolon_before_statement/index.html b/files/vi/web/javascript/reference/errors/missing_semicolon_before_statement/index.html deleted file mode 100644 index 2e5e606618..0000000000 --- a/files/vi/web/javascript/reference/errors/missing_semicolon_before_statement/index.html +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: 'Lỗi cú pháp: Thiếu dấu ; trước câu lệnh' -slug: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement -tags: - - JavaScript - - Lỗi - - Lỗi cú pháp -translation_of: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement ---- -
{{jsSidebar("Errors")}}
- -

Thông điệp

- -
SyntaxError: missing ; before statement
-
- -

Kiểu lỗi

- -

{{jsxref("Lỗi cú pháp")}}.

- -

Sai ở đâu?

- -

Bạn đang thiếu dấu (;) ở đâu đó. Câu lệnh JavaScript phải được kết thúc bằng một dấu "chấm phẩy". Một vài trong số đó được thêm tự động bởi tính năng automatic semicolon insertion (ASI), nhưng trong tình huống này bạn cần thêm thủ công để JavaScript có thể hiểu câu lệnh của bạn chính xác.

- -

Tuy nhiên, thi thoảng lỗi này lại là kết quả của một vài lỗi khác, ví dụ như không kết thúc chuỗi ký tự một cách chính xác, hoặc sử dụng từ khoá var không đúng. Cũng có thể bạn đã thêm quá nhiều dấu ngoặc tròn ở đâu đó. Nếu bạn nhìn thấy lỗi này, trước hết hãy kiểm tra cẩn thận các lỗi cú pháp.

- -

Ví dụ

- -

Không kết thúc chuỗi

- -

Lỗi này có thể xảy ra khi bạn quên kết thúc chuỗi, còn JavaScrip thì đang mong đợi điều ấy:

- -
var foo = 'Tom's bar';
-// SyntaxError: missing ; before statement
- -

Bạn có thể sử dụng dấu nháy kép hoặc sử dụng dấu  \ cho những ký tự đặc biệt thế này:

- -
var foo = "Tom's bar";
-var foo = 'Tom\'s bar';
-
- -

Khai báo thuộc tính với từ khoá var

- -

Bạn KHÔNG THỂ khai báo thuộc tính của một đối tượng hoặc một mảng bằng từ khoá var:

- -
var obj = {};
-var obj.foo = 'hi'; // SyntaxError missing ; before statement
-
-var array = [];
-var array[0] = 'there'; // SyntaxError missing ; before statement
-
- -

Thay vào đó, hãy cứ bỏ qua từ khoá var như thế này:

- -
var obj = {};
-obj.foo = 'hi';
-
-var array = [];
-array[0] = 'there';
-
- -

Xem thêm:

- - diff --git a/files/vi/web/javascript/reference/errors/more_arguments_needed/index.html b/files/vi/web/javascript/reference/errors/more_arguments_needed/index.html deleted file mode 100644 index 4cf87a8b6d..0000000000 --- a/files/vi/web/javascript/reference/errors/more_arguments_needed/index.html +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: 'TypeError: More arguments needed' -slug: Web/JavaScript/Reference/Errors/More_arguments_needed -translation_of: Web/JavaScript/Reference/Errors/More_arguments_needed ---- -
{{jsSidebar("Errors")}}
- -

Message

- -
TypeError: tham số không phải là một đối tượng và không phải là null (Edge)
-TypeError: Object.create requires cần ít nhất 1 tham số, nhưng chỉ có 0 được thông qua
-TypeError: Object.setPrototypeOf requires cần ít nhất 2 tham số nhưng chỉ có 0 được thông qua
-TypeError: Object.defineProperties requires cần ít nhất một tham số, nhưng chỉ có 0 được thông qua
-
- -

Loại lỗi

- -

{{jsxref("Lỗi")}}.

- -

Chuyện gì đã xảy ra?

- -

Đã có một lỗi với hàm được gọi. Cần cung cấp nhiều tham số hơn

- -

VÍ dụ

- -

Phương thức {{jsxref("Object.create()")}} cần ít nhất 1 tham số và phương thức {{jsxref("Object.setPrototypeOf()")}} cần ít nhất 2 tham số:

- -
var obj = Object.create();
-// TypeError: Object.create requires cần ít nhất là 1 tham số, nhưng chỉ có 0 được thông qua
-
-var obj = Object.setPrototypeOf({});
-// TypeError: Object.setPrototypeOf requires cần ít nhât 2 tham số, nhưng chỉ có 1 được thông qua
-
- -

Bạn có thể khắc phục bằng cách đặt {{jsxref("null")}} về nguyên mẫu, ví dụ:

- -
var obj = Object.create(null);
-
-var obj = Object.setPrototypeOf({}, null);
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/errors/not_a_function/index.html b/files/vi/web/javascript/reference/errors/not_a_function/index.html deleted file mode 100644 index a267a8bc74..0000000000 --- a/files/vi/web/javascript/reference/errors/not_a_function/index.html +++ /dev/null @@ -1,84 +0,0 @@ ---- -title: 'TypeError: "x" is not a function' -slug: Web/JavaScript/Reference/Errors/Not_a_function -tags: - - JavaScript - - Lỗi - - Lỗi đánh máy -translation_of: Web/JavaScript/Reference/Errors/Not_a_function ---- -
{{jsSidebar("Errors")}}
- -

Message

- -
TypeError: "x" is not a function
-
- -

Thể loại sai:

- -

{{jsxref("TypeError")}}.

- -

Chuyện gì đã xảy ra?

- -

Dự định gọi 1 giá trị như 1 chức năng, nhưng giá trị đó không thật sự là 1 chức năng. Một số đoạn mã chờ bạn cung cấp 1 chức năng, nhưng điều đó không xảy ra.

- -

Có lẽ là do bạn đánh sai tên chức năng chăng? Có lẽ object mà bạn định gọi method cho không có chức năng này? Ví dụ như những object của Javascript không có chức năng map, nhưng object của Javascript xâu (Array) thì có.

- -

Có rất nhiều chức năng có sẵn khi cần dùng lại 1 chức năng. Bạn sẽ phải cung cấp 1 chức năng để những method này hoạt động 1 cách chính xác.

- - - -

Ví dụ

- -

Lỗi đánh máy trong tên chức năng

- -

Trong trường hợp này, xảy ra rất thường xuyên, có 1 lỗi đánh máy trong tên method:

- -
var x = document.getElementByID('foo');
-// TypeError: document.getElementByID is not a function
-
- -

Tên đúng là getElementById:

- -
var x = document.getElementById('foo');
-
- -

Chức năng bị gọi sai trên object

- -

Đối với 1 số method nhất định, bạn phải cung cấp 1 chức năng (để gọi trở lại) và nó sẽ hoạt động trên những object nhất định đó thôi. Ví dụ khi {{jsxref("Array.prototype.map()")}} được sử dụng, thì sẽ chỉ chạy với object {{jsxref("Array")}} này mà thôi.

- -
var obj = {a: 13, b: 37, c: 42};
-
-obj.map(function(num) {
-  return num * 2;
-});
-
-// TypeError: obj.map is not a function
- -

Thay vào đó, sử dụng 1 xâu:

- -
var numbers = [1, 4, 9];
-
-numbers.map(function(num) {
-  return num * 2;
-});
-
-// Array [2, 8, 18]
-
- -

Liên kết:

- - diff --git a/files/vi/web/javascript/reference/errors/too_much_recursion/index.html b/files/vi/web/javascript/reference/errors/too_much_recursion/index.html deleted file mode 100644 index 32084a7de0..0000000000 --- a/files/vi/web/javascript/reference/errors/too_much_recursion/index.html +++ /dev/null @@ -1,55 +0,0 @@ ---- -title: 'InternalError: Quá nhiều đệ quy' -slug: Web/JavaScript/Reference/Errors/Too_much_recursion -tags: - - JavaScript - - Lỗi - - Lỗi bên trong -translation_of: Web/JavaScript/Reference/Errors/Too_much_recursion -original_slug: Web/JavaScript/Reference/Errors/qua_nhieu_de_quy ---- -
{{jsSidebar("Errors")}}
- -

Thông điệp

- -
InternalError: too much recursion
-
- -

Loại lỗi

- -

{{jsxref("InternalError")}}.

- -

Lỗi phát sinh ra khi nào?

- -

Một hàm gọi chính nó được gọi là hàm đệ quy . Trong một số trường hợp, đệ quy tương tự như một vòng lặp. Cả hai đều thực hiện cùng một mã nhiều lần, Và cả hai đều yêu cầu một điều kiện ( Để tránh một vòng lặp vô hạn, hoặc đúng hơn, đệ quy vô hạn trong trường hợp này ). Khi có quá nhiều hoặc vô hạn đệ quy, JavaScript sẽ ném lỗi này.

- -

Ví dụ

- -

Chức năng đệ quy này chạy 10 lần, theo điều kiện x >= 10 .

- -
function loop(x) {
-  if (x >= 10) // "x >= 10" là điều kiện dừng
-    return;
-  // do stuff
-  loop(x + 1); // gọi lại chính nó (đệ quy)
-}
-loop(0);
- -

Đặt điều kiện này lên một giá trị rất cao, sẽ không hoạt động:

- -
function loop(x) {
-  if (x >= 1000000000000)
-    return;
-  // do stuff
-  loop(x + 1);
-}
-loop(0);
-
-// InternalError: too much recursion
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/functions/arguments/index.html b/files/vi/web/javascript/reference/functions/arguments/index.html deleted file mode 100644 index ffcb00b472..0000000000 --- a/files/vi/web/javascript/reference/functions/arguments/index.html +++ /dev/null @@ -1,234 +0,0 @@ ---- -title: The arguments object -slug: Web/JavaScript/Reference/Functions/arguments -translation_of: Web/JavaScript/Reference/Functions/arguments ---- -

{{JSSidebar("Functions")}}

- -

arguments là object giống Array khả truy cập bên trong hàm, chứa các giá trị của đối số truyền vào trong hàm đó.

- -
-

Ghi chú: Nếu bạn viết mã tương thích cho ES6, thì bạn nên tham khảo rest parameters.

-
- -
-

Ghi chú: “Giống Array” tức là arguments có thuộc tính {{jsxref("Functions/arguments/length", "length")}} và đánh chỉ mục từ không (0), nhưng nó không có phương thức dựng sẵn của {{JSxRef("Array")}} như {{jsxref("Array.forEach", "forEach()")}} và {{jsxref("Array.map", "map()")}}. Xem §Mô tả để biết thêm chi tiết.

-
- -
{{EmbedInteractiveExample("pages/js/functions-arguments.html")}}
- - - -

Cú pháp

- -
arguments
- -

Mô tả

- -

Object arguments là biến cục bộ có sẵn cho mọi hàm không phải hàm mũi tên. Bạn có thể tham chiếu tới đối số của một hàm bên trong hàm đó bằng cách sử dụng object arguments. Nó chứa từng đối số mà hàm đó được gọi cùng, với chỉ mục bắt đầu từ 0.

- -

Chẳng hạn, nếu một hàm được truyền vào 3 đối số, bạn có thể truy cập nó theo cách sau:

- -
arguments[0] // đối số thứ nhất
-arguments[1] // đối số thứ hai
-arguments[2] // đối số thứ ba
-
- -

Mỗi đối số đều có thể thiết lập hoặc gán lại:

- -
arguments[1] = 'new value';
-
- -

Object arguments không phải là {{jsxref("Array")}}. Nó tương tự nhưng không có thuộc tính của Array ngoài {{jsxref("Array.length", "length")}}. Chẳng hạn, nó không có phương thức {{jsxref("Array.pop", "pop()")}}. Tuy nhiên, nó có thể ép kiểu về Array:

- -
var args = Array.prototype.slice.call(arguments);
-// Using an array literal is shorter than above but allocates an empty array
-var args = [].slice.call(arguments);
-
- -

Như có thể làm với mọi object giống-Array, bạn có thể dùng phương thức {{jsxref("Array.from()")}} của ES2015 hoặc cú pháp spread để ép kiểu arguments thành Array:

- -
var args = Array.from(arguments);
-var args = [...arguments];
-
- -

Object arguments có ích đối với hàm được truyền nhiều đối số hơn so với khởi tạo ban đầu. Kỹ thuật này có ích với hàm cần được truyền nhiều biến, như là {{jsxref("Math.min()")}}. Hàm ví dụ dưới đây chấp nhật mọi xâu ký tự và trả về xâu dài nhất:

- -
function longestString() {
-  var longest = '';
-  for (var i=0; i < arguments.length; i++) {
-    if (arguments[i].length > longest.length) {
-      longest = arguments[i];
-    }
-  }
-  return longest;
-}
-
- -

Bạn có thể dùng {{jsxref("Functions/arguments/length", "arguments.length")}} để đếm số lượng đối số được truyền vào khi hàm được gọi. Thay vì thế, nếu bạn muốn đếm số lượng tham số chính quy mà hàm chấp nhận khi khởi tạo, hãy tham khảo thuộc tính {{jsxref("Function.length", "length")}} của hàm.

- -

Sử dụng typeof với Arguments

- -

Toán tử {{jsxref("Operators/typeof", "typeof")}} trả về 'object' khi dùng với arguments

- -
console.log(typeof arguments); // 'object' 
- -

Kiểu của từng đối số có thể xác định lần lượt bằng cách chỉ đích danh trong object arguments:

- -
console.log(typeof arguments[0]); // trả về kiểu của đối số thứ nhất
- -

Thuộc tính

- -
-
{{jsxref("Functions/arguments/callee", "arguments.callee")}}
-
Tham chiếu tới hàm đang được thực thi sở hữu arguments.
-
{{jsxref("Functions/arguments/caller", "arguments.caller")}} {{Obsolete_Inline}}
-
Reference to the function that invoked the currently executing function.
-
{{jsxref("Functions/arguments/length", "arguments.length")}}
-
Số lượng đối số được truyền vào hàm.
-
{{jsxref("Functions/arguments/@@iterator", "arguments[@@iterator]")}}
-
Returns a new {{jsxref("Array/@@iterator", "Array iterator", "", 0)}} object that contains the values for each index in the arguments.
-
- -

Ví dụ

- -

Định nghĩa hàm nối xâu ký tự

- -

Ví dụ sau đây định nghĩa một hàm nối các xâu ký tự với nhau. Tham số chính quy mà hàm nhận là một xâu chứa các ký tự ngăn cách các xâu với nhau sau khi được nối.

- -
function myConcat(separator) {
-  var args = Array.prototype.slice.call(arguments, 1);
-  return args.join(separator);
-}
- -

Bạn có thể truyền vào bao nhiêu xâu ký tự tuỳ ý. Giá trị trả về là một xâu chứa tất cả các đối số được truyền vào:

- -
// trả về "red, orange, blue"
-myConcat(', ', 'red', 'orange', 'blue');
-
-// trả về "elephant; giraffe; lion; cheetah"
-myConcat('; ', 'elephant', 'giraffe', 'lion', 'cheetah');
-
-// trả về "sage. basil. oregano. pepper. parsley"
-myConcat('. ', 'sage', 'basil', 'oregano', 'pepper', 'parsley');
- -

Định nghĩa hàm sinh danh sách HTML

- -

Ví dụ sau đây định nghĩa một hàm sinh ra một xâu ký tự chứa các thẻ HTML để tạo thành một danh sách. Tham số chính quy duy nhất mà hàm nhận là một ký tự như "u" nếu danh sách không có thứ tự (đánh dấu chấm), hay "o" nếu danh sách có thứ tự (đánh số). Hàm đó được định nghĩa như sau:

- -
function list(type) {
-  var html = '<' + type + 'l><li>';
-  var args = Array.prototype.slice.call(arguments, 1);
-  html += args.join('</li><li>');
-  html += '</li></' + type + 'l>'; // end list
-
-  return html;
-}
- -

Bạn có thể truyền bao nhiêu đối số tuỳ ý, và nó sẽ thêm từng đối số vào danh sách có kiểu xác định trước. Chẳng hạn:

- -
var listHTML = list('u', 'One', 'Two', 'Three');
-
-/* listHTML is:
-"<ul><li>One</li><li>Two</li><li>Three</li></ul>"
-*/
- -

Tham số rest, default và destructured

- -

Object arguments có thể dùng cùng lúc với các tham số như rest, default, và destructured.

- -
function foo(...args) {
-  return args;
-}
-foo(1, 2, 3); // [1,2,3]
-
- -

Tuy trong strict-mode, tham số rest, default, hoặc destructured parameters không can thiệp vào hành vi của object arguments, nhưng trong non-strict mode vẫn có không ít khác biệt.

- -

Nếu một hàm non-strict không chứa tham số rest, default, hay destructured, thì giá trị trong object arguments thay đổi đồng bộ với giá trị của tham số truyền vào. Hãy xem đoạn mã dưới đây:

- -
function func(a) {
-  arguments[0] = 99; // cập nhật arguments[0] cũng cập nhật a
-  console.log(a);
-}
-func(10); // 99
-
- -

- -
function func(a) {
-  a = 99; // cập nhật a cũng cập nhật arguments[0]
-  console.log(arguments[0]);
-}
-func(10); // 99
-
- -

Khi hàm non-strict chứa tham số rest, default hoặc destructured, thì giá trị trong object arguments không theo dõi giá trị của đối số. Thay vì vậy, chúng ánh xạ đến đối số truyền vào khi hàm được gọi:

- -
function func(a = 55) {
-  arguments[0] = 99; // updating arguments[0] does not also update a
-  console.log(a);
-}
-func(10); // 10
- -

- -
function func(a = 55) {
-  a = 99; // updating a does not also update arguments[0]
-  console.log(arguments[0]);
-}
-func(10); // 10
-
- -

- -
// An untracked default parameter
-function func(a = 55) {
-  console.log(arguments[0]);
-}
-func(); // undefined
- -

Đặc tả kĩ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1
{{SpecName('ES5.1', '#sec-10.6', 'Arguments Object')}}{{Spec2('ES5.1')}} 
{{SpecName('ES2015', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}{{Spec2('ES2015')}} 
{{SpecName('ESDraft', '#sec-arguments-exotic-objects', 'Arguments Exotic Objects')}}{{Spec2('ESDraft')}} 
- -

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

- - - -

{{Compat("javascript.functions.arguments")}}

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/functions/arrow_functions/index.html b/files/vi/web/javascript/reference/functions/arrow_functions/index.html deleted file mode 100644 index 6da70e4205..0000000000 --- a/files/vi/web/javascript/reference/functions/arrow_functions/index.html +++ /dev/null @@ -1,426 +0,0 @@ ---- -title: Hàm mũi tên (hàm rút gọn) -slug: Web/JavaScript/Reference/Functions/Arrow_functions -translation_of: Web/JavaScript/Reference/Functions/Arrow_functions ---- -
{{jsSidebar("Functions")}}
- -

Biểu thức hàm mũi tên là một thay thế rút gọn cho hàm biểu thức truyền thống, nhưng bị hạn chế và không thể sử dụng trong mọi trường hợp.

- -

Sự khác biệt & Hạn chế:

- - - -

{{EmbedInteractiveExample("pages/js/functions-arrow.html")}}

- -

So sánh hàm truyền thống và hàm mũi tên

- -

Hãy phân tách "hàm truyền thống" thành "hàm mũi tên" đơn giản nhất theo từng bước:
- LƯU Ý: Mỗi bước là một "hàm mũi tên" hợp lệ.

- -
// Hàm truyền thống
-function (a){
-  return a + 100;
-}
-
-// Phân rã thành hàm mũi tên
-
-// 1. Xóa từ khóa "function" và thay thế bằng mũi tên ở giữa đối số và dấu ngoặc nhọn bắt đầu nội dung hàm
-(a) => {
-  return a + 100;
-}
-
-// 2. Xóa dấu ngoặc nhọn và từ khóa "return" sự trả về đã bao hàm (mặc định) khi sử dụng hàm mũi tên.
-(a) => a + 100;
-
-// 3. Xóa luôn dấu ngoặc đơn của đối số
-a => a + 100;
- -

Như bạn thấy ở bên trên, dấu { ngoặc nhọn } và dấu (ngoặc tròn ở đối ố) và "return" là tùy chọn, nhưng đôi khi có thể bắt buộc phải có.

- -

Ví dụ, nếu bạn có nhiều đối số hoặc không có đối số, bạn cần phải thêm dấu ngoặc tròn vào xung quanh các đối số:

- -
// Hàm Truyền thống
-function (a, b){
-  return a + b + 100;
-}
-
-// Hàm mũi tên
-(a, b) => a + b + 100;
-
-// Hàm truyền thống (không đối số)
-let a = 4;
-let b = 2;
-function (){
-  return a + b + 100;
-}
-
-// Hàm mũi tên (không đối số)
-let a = 4;
-let b = 2;
-() => a + b + 100;
- -

Tương tự như vậy, nếu nội dung (body) hàm cần thêm nhiều dòng để xử lý thì bạn cần thêm vào dấu ngoặc nhọn CỘNG thêm "return" (hàm mũi tên không có kỳ diệu đến mức biết khi nào bạn muốn "return"):

- -
// Hàm truyền thống
-function (a, b){
-  let chuck = 42;
-  return a + b + chuck;
-}
-
-// Hàm mũi tên
-(a, b) => {
-  let chuck = 42;
-  return a + b + chuck;
-}
- -

Và cuối cùng, với các hàm được đặt tên chúng tôi xử lý các biểu thức mũi tên như các biến

- -
// Hàm truyền thống
-function bob (a){
-  return a + 100;
-}
-
-// Hàm mũi tên
-let bob = a => a + 100;
- -

Cú pháp

- -

Cú pháp cơ bản

- -
(param1, param2, …, paramN) => { statements }
-(param1, param2, …, paramN) => expression
-// tương đương với: (param1, param2, …, paramN) => { return expression; }
-
-// Dấu ngoặc đơn không bắt buộc khi chỉ có một tham số truyền vào:
-(singleParam) => { statements }
-singleParam => { statements }
-
-// Hàm khi không có tham số truyền vào bắt buộc phải là dấu ():
-() => { statements }
-() => expression // tương đương: () => { return expression; }
-
- -

Cú pháp nâng cao

- -
// Bên trong dấu ngoặc đơn là một đối tượng:
-params => ({foo: bar})
-
-// Rest parameters và default parameters được hỗ trợ
-(param1, param2, ...rest) => { statements }
-(param1 = defaultValue1, param2, …, paramN = defaultValueN) => { statements }
-
-// Destructuring within the parameter list is also supported
-var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
-f();  // 6
-
- -

Chi tiết các ví dụ bạn có thể xem ở đây.

- -

Mô tả

- -

Xem thêm "ES6 Chuyên sâu: Những hàm arrow" trên hacks.mozilla.org.

- -

Two factors influenced the introduction of arrow functions: shorter functions and non-binding of this.

- -

Hàm ngắn

- -

Một vài ví dụ, cú pháp hàm rút gọn luôn được coder yêu thích, cùng so sánh:

- -
var materials = [
-  'Hydrogen',
-  'Helium',
-  'Lithium',
-  'Beryllium'
-];
-
-// thông thường
-var materialsLength1 = materials.map(function(material) {
-  return material.length;
-});
-
-// ngắn hơn (như mùa đông 5 độ vậy)
-var materialsLength2 = materials.map((material) => {
-  return material.length;
-});
-
-// ngắn hơn nữa (và -2 độ, bạn còn bao nhiêu cm ?)
-var materialsLength3 = materials.map(material => material.length);
-
- -

Không ràng buộc this

- -

Cho tới khi hàm rút gọn xuất hiện, mọi hàm mới đều tự định nghĩa giá trị this của riêng hàm (là object vừa được khởi tạo nếu dùng constructor, là undefined nếu đặt strict mode khi gọi hàm, là context object nếu hàm được gọi như một "object method", vân vân.). This trở nên khá khó chịu khi làm việc với phong cách lập trình hướng đối tượng.

- -
function Person() {
-  // constructor của Person() định nghĩa `this` như một biến.
-  this.age = 0;
-
-  setInterval(function growUp() {
-    // Khi dùng non-strict mode, hàm growUp() định nghĩa `this`
-    // như một đối tượng toàn cục, khác hoàn toàn so với `this`
-    // được định nghĩa bởi constructor của Person().
-    this.age++;
-  }, 1000);
-}
-
-var p = new Person();
- -

Theo ECMAScript 3/5, vấn đề của this có thể sửa được bằng cách gán this cho một biến gần nhất.

- -
function Person() {
-  var that = this;
-  that.age = 0;
-
-  setInterval(function growUp() {
-    // Hàm callback trỏ tới biến `that`với
-    // giá trị là đối tượng mong đợi.
-    that.age++;
-  }, 1000);
-}
- -

Nói cách khác, tạo ra một hàm ràng buộc để truyền giá trị của this vào hàm ràng buộc đích (chẳng hạn như hàm growUp() phía trên).

- -

Hàm rút gọn không tạo ra ngữ cảnh this của riêng hàm, thế nên this có ý nghĩa trong ngữ cảnh bọc quanh nó. Đoạn code phía dưới là một ví dụ:

- -
function Person(){
-  this.age = 0;
-
-  setInterval(() => {
-    this.age++; // |this| ở đây trỏ tới đối tượng person
-  }, 1000);
-}
-
-var p = new Person();
- -

Mối liên hệ với strict mode

- -

Giả sử this bị bó buộc trong thân hàm, strict mode sẽ khiến cho this bị bỏ qua.

- -
var f = () => { 'use strict'; return this; };
-f() === window; // hoặc đối tượng toàn cục
- -

Các strict mode khác được áp dụng như bình thường.

- -

Gọi thông qua call hoặc apply

- -

Vì this không bị ràng buộc bên trong hàm rút gọn, các phương thức call() hoặc apply() chỉ có thể truyền tham số. this bị bỏ qua.

- -
var adder = {
-  base: 1,
-
-  add: function(a) {
-    var f = v => v + this.base;
-    return f(a);
-  },
-
-  addThruCall: function(a) {
-    var f = v => v + this.base;
-    var b = {
-      base: 2
-    };
-
-    return f.call(b, a);
-  }
-};
-
-console.log(adder.add(1));         // Sẽ trả ra 2
-console.log(adder.addThruCall(1)); // Vẫn sẽ trả ra 2
- -

Không ràng buộc arguments

- -

Hàm rút gọn không ràng buộc arguments object. Do đó, trong ví dụ sau, arguments chỉ đơn giản là một tham chiếu đến đối tượng cùng tên trong phạm vi bao quanh:

- -
var arguments = 42;
-var arr = () => arguments;
-
-arr(); // 42
-
-function foo() {
-  var f = (i) => arguments[0] + i; // foo's implicit arguments binding
-  return f(2);
-}
-
-foo(1); // 3
- -

Trong nhiều trường hợp, sử dụng rest parameters là một cách thay thế tốt để dùng đối tượng arguments.

- -
function foo() {
-  var f = (...args) => args[0];
-  return f(2);
-}
-
-foo(1); // 2
- -

Dùng hàm rút gọn như một phương thức

- -

Như đã nói phía trên, biểu thức hàm rút gọn cực kì hợp với các hàm non-method. Hãy xem chuyện gì sẽ xảy ra khi ta dùng chúng như phương thức trong ví dụ bên dưới nhé:

- -
'use strict';
-var obj = {
-  i: 10,
-  b: () => console.log(this.i, this),
-  c: function() {
-    console.log(this.i, this);
-  }
-}
-obj.b(); // in ra undefined, Object {...}
-obj.c(); // in ra 10, Object {...}
- -

Hàm rút gọn không định nghĩa ("ràng buộc") this của hàm.  Một ví dụ khác đối với {{jsxref("Object.defineProperty()")}}:

- -
'use strict';
-var obj = {
-  a: 10
-};
-
-Object.defineProperty(obj, 'b', {
-  get: () => {
-    console.log(this.a, typeof this.a, this);
-    return this.a + 10; // đại diện cho đối tượng toàn cục 'Window', bởi vậy 'this.a' trả về 'undefined'
-  }
-});
-
- -

Dùng toán tử new

- -

Hàm rút gọn không thể dùng như phương thức khởi tạo và sẽ báo lỗi nếu dùng toán tử new.

- -
var Foo = () => {};
-var foo = new Foo(); // TypeError: Foo is not a constructor
- -

Dùng thuộc tính prototype

- -

Hàm rút gọn không có thuộc tính prototype.

- -
var Foo = () => {};
-console.log(Foo.prototype); // undefined
-
- -

Dùng từ khoá yield

- -

Từ khoá yield có thể sẽ không dùng được trong thân hàm rút gọn (trừ khi được gọi trong hàm lồng trong hàm rút gọn). Tức là, hàm rút gọn không thể dùng như là generator (hàm sinh).

- -

Phần thân hàm

- -

Hàm rút gọn vừa có thể có "concise body" hoặc dạng thường thấy "block body".

- -

Trong concise body, chỉ cần biểu thức, return sẽ được gán ngầm. Còn với block body, bạn phải có return.

- -
var func = x => x * x;                  // concise syntax, implied "return"
-var func = (x, y) => { return x + y; }; // with block body, explicit "return" needed
-
- -

Trả về object literals

- -

Không thể dùng cú pháp params => {object:literal} nếu muốn trả về object literal.

- -
var func = () => { foo: 1 };               // Calling func() returns undefined!
-var func = () => { foo: function() {} };   // SyntaxError: function statement requires a name
- -

Bởi vì đoạn code bên trong ({}) được phân giải thành một chuỗi các trình tự nối tiếp (ví dụ foo được coi như một nhãn, thay vì một key trong object literal).

- -

Thế nên hãy bao object literal trong ngoặc tròn.

- -
var func = () => ({foo: 1});
- -

Kí tự xuống dòng

- -

Hàm rút gọn không thể chứa bất cứ kí tự rút gọn nào giữa phần truyền tham số và dấu mũi tên.

- -
var func = ()
-           => 1; // SyntaxError: expected expression, got '=>'
- -

Parsing order

- -

Although the arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently with operator precedence compared to regular functions.

- -
let callback;
-
-callback = callback || function() {}; // ok
-callback = callback || () => {};      // SyntaxError: invalid arrow-function arguments
-callback = callback || (() => {});    // ok
-
- -

Một số ví dụ khác

- -
// An empty arrow function returns undefined
-let empty = () => {};
-
-(() => 'foobar')(); // IIFE, returns "foobar"
-
-var simple = a => a > 15 ? 15 : a;
-simple(16); // 15
-simple(10); // 10
-
-let max = (a, b) => a > b ? a : b;
-
-// Easy array filtering, mapping, ...
-
-var arr = [5, 6, 13, 0, 1, 18, 23];
-var sum = arr.reduce((a, b) => a + b);  // 66
-var even = arr.filter(v => v % 2 == 0); // [6, 0, 18]
-var double = arr.map(v => v * 2);       // [10, 12, 26, 0, 2, 36, 46]
-
-// More concise promise chains
-promise.then(a => {
-  // ...
-}).then(b => {
-   // ...
-});
-
-// Parameterless arrow functions that are visually easier to parse
-setTimeout( () => {
-  console.log('I happen sooner');
-  setTimeout( () => {
-    // deeper code
-    console.log('I happen later');
-  }, 1);
-}, 1);
-
- -

Đặc điểm kĩ thuật

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-arrow-function-definitions', 'Arrow Function Definitions')}}{{Spec2('ESDraft')}}
- -

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

- -
{{Compat("javascript.functions.arrow_functions")}}
- -

Firefox-specific notes

- - - -

Tìm đọc

- - diff --git a/files/vi/web/javascript/reference/functions/default_parameters/index.html b/files/vi/web/javascript/reference/functions/default_parameters/index.html deleted file mode 100644 index 11ae77dab7..0000000000 --- a/files/vi/web/javascript/reference/functions/default_parameters/index.html +++ /dev/null @@ -1,198 +0,0 @@ ---- -title: Default parameters -slug: Web/JavaScript/Reference/Functions/Default_parameters -translation_of: Web/JavaScript/Reference/Functions/Default_parameters ---- -
{{jsSidebar("Functions")}}
- -

Các tham số của hàm mặc định cho phép khởi tạo với các giá trị mặc định khi không truyền giá trị vào đó.

- -
{{EmbedInteractiveExample("pages/js/functions-default.html")}}
- - - -

Cú pháp

- -
function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) {
-   statements
-}
-
- -

Mô tả

- -

Trong JavaScript, tham số của hàm mặc định {{jsxref("undefined")}}. Tuy nhiên, chúng thường hữu ích hơn khi tạo giá trị mặc định khác. 

- -

Trước đây, quy tắc chung khi tạo giá trị mặc định là kiểm tra các giá trị tham số trong thân hàm và gán vào tham số nếu nó không xác định.

- -

Trong ví dụ sau, nếu không cung cấp giá trị cho b khi gọi hàm multiply, b sẽ không xác định trong phép tính a * b và hàm multiply sẽ trả về NaN.

- -
function multiply(a, b) {
-  return a * b;
-}
-
-multiply(5, 2); // 10
-multiply(5);    // NaN !
-
- -

Để tránh điều này, ta sẽ dùng một dòng code xác định b=1 nếu hàm chỉ được gọi với 1 đối số.

- -
function multiply(a, b) {
-  b = (typeof b !== 'undefined') ?  b : 1;
-  return a * b;
-}
-
-multiply(5, 2); // 10
-multiply(5);    // 5
-
- -

Với các tham số mặc định trong ES2015, việc kiểm tra thân hàm không còn cần thiết. Bạn có thể gán 1 cho b ở đầu hàm:

- -
function multiply(a, b = 1) {
-  return a * b;
-}
-
-multiply(5, 2); // 10
-multiply(5);    // 5
-
- -

Ví dụ

- -

Truyền giá trị undefined với giá trị ảo

- -

Trong lời gọi thứ hai, ngay cả khi đối số thứ nhất không xác định (không phải null hay giá trị ảo), đối số num vẫn mặc định.

- -

function test(num = 1) { console.log(typeof num); } test(); // 'number' (num is set to 1) test(undefined); // 'number' (num is set to 1 too) // test with other falsy values: test(''); // 'string' (num is set to '') test(null); // 'object' (num is set to null)

- -

Xét tại thời điểm gọi

- -

Đối số mặc định được xét tại thời điểm gọi. Trong khi Python, một đối tượng mới được tạo ra mỗi khi hàm được gọi.

- -

function append(value, array = []) { array.push(value); return array; } append(1); //[1] append(2); //[2], not [1, 2]

- -

Áp dụng cho cả hàm và biến:

- -
function callSomething(thing = something()) {
- return thing;
-}
-
-let numberOfTimesCalled = 0;
-function something() {
-  numberOfTimesCalled += 1;
-  return numberOfTimesCalled;
-}
-
-callSomething(); // 1
-callSomething(); // 2
- -

Các tham số mặc định có sẵn cho các tham số mặc định sau:

- -

Các tham số được xác định trước (bên trái) có sẵn cho các tham số mặc định sau:

- -

function greet(name, greeting, message = greeting + ' ' + name) {     return [name, greeting, message]; } greet('David', 'Hi');  // ["David", "Hi", "Hi David"] greet('David', 'Hi', 'Happy Birthday!');  // ["David", "Hi", "Happy Birthday!"]

- -

This functionality can be aChức năng này sử dụng cho nhiều trường hợp xảy ra:

- -
function go() {
-  return ':P';
-}
-
-function withDefaults(a, b = 5, c = b, d = go(), e = this,
-                      f = arguments, g = this.value) {
-  return [a, b, c, d, e, f, g];
-}
-
-function withoutDefaults(a, b, c, d, e, f, g) {
-  switch (arguments.length) {
-    case 0:
-      a;
-    case 1:
-      b = 5;
-    case 2:
-      c = b;
-    case 3:
-      d = go();
-    case 4:
-      e = this;
-    case 5:
-      f = arguments;
-    case 6:
-      g = this.value;
-    default:
-  }
-  return [a, b, c, d, e, f, g];
-}
-
-withDefaults.call({value: '=^_^='});
-// [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="]
-
-withoutDefaults.call({value: '=^_^='});
-// [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="]
-
- -

Định nghĩa hàm trong thân hàm

- -

Giới thiệu trong Gecko 33 {{geckoRelease(33)}}. Các hàm được khai báo trong thân hàm không thể được tham chiếu bên trong với các tham số mặc định của hàm ngoài. Nếu bạn thử, {{jsxref("ReferenceError")}} sẽ bị loại bỏ. Các tham số mặc định luôn được thực thi trước, hàm khai báo bên trong thân hàm sẽ thực thi sau.

- -
// Doesn't work! Throws ReferenceError.
-function f(a = go()) {
-  function go() { return ':P'; }
-}
-
- -

Tham số không mặc định

- -

Trước Gecko 26 {{geckoRelease(26)}}, đoạn code sau cho kết quả {{jsxref("SyntaxError")}}. Sau đó được sửa lại {{bug(777060)}}. Các tham số vẫn xuất hiện từ trái qua phải, ghi đè lên các tham số mặc định kể cả các tham số sau không mặc định.

- -
function f(x = 1, y) {
-  return [x, y];
-}
-
-f(); // [1, undefined]
-f(2); // [2, undefined]
-
- -

Tham số bị hủy gán với giá trị mặc định

- -

Có thể dùng giá trị mặc định với kí hiệu destructuring assignment:

- -
function f([x, y] = [1, 2], {z: z} = {z: 3}) {
-  return x + y + z;
-}
-
-f(); // 6
- -

Đặc điểm

- - - - - - - - - - - - - - - - - - - -
Đặc điểmTrạng tháiGhi chú
{{SpecName('ES2015', '#sec-function-definitions', 'Function Definitions')}}{{Spec2('ES2015')}}Định nghĩa ban đầu
{{SpecName('ESDraft', '#sec-function-definitions', 'Function Definitions')}}{{Spec2('ESDraft')}}
- -

Trình duyệt tương thích

- -
- - -

{{Compat("javascript.functions.default_parameters")}}

-
- -

Liên quan

- - diff --git a/files/vi/web/javascript/reference/functions/index.html b/files/vi/web/javascript/reference/functions/index.html deleted file mode 100644 index e7935d3318..0000000000 --- a/files/vi/web/javascript/reference/functions/index.html +++ /dev/null @@ -1,657 +0,0 @@ ---- -title: Functions -slug: Web/JavaScript/Reference/Functions -tags: - - Constructor - - Function - - Functions - - JavaScript - - NeedsTranslation - - Parameter - - TopicStub - - parameters -translation_of: Web/JavaScript/Reference/Functions ---- -
{{jsSidebar("Functions")}}
- -

Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function will return a value.

- -

In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.

- -

For more examples and explanations, see also the JavaScript guide about functions.

- -

Description

- -

Every function in JavaScript is a Function object. See {{jsxref("Function")}} for information on properties and methods of Function objects.

- -

To return a value other than the default, a function must have a return statement that specifies the value to return. A function without a return statement will return a default value. In the case of a constructor called with the new keyword, the default value is the value of its this parameter. For all other functions, the default return value is {{jsxref("undefined")}}.

- -

The parameters of a function call are the function's arguments. Arguments are passed to functions by value. If the function changes the value of an argument, this change is not reflected globally or in the calling function. However, object references are values, too, and they are special: if the function changes the referred object's properties, that change is visible outside the function, as shown in the following example:

- -
/* Declare the function 'myFunc' */
-function myFunc(theObject) {
-   theObject.brand = "Toyota";
- }
-
- /*
-  * Declare variable 'mycar';
-  * create and initialize a new Object;
-  * assign reference to it to 'mycar'
-  */
- var mycar = {
-   brand: "Honda",
-   model: "Accord",
-   year: 1998
- };
-
- /* Logs 'Honda' */
- console.log(mycar.brand);
-
- /* Pass object reference to the function */
- myFunc(mycar);
-
- /*
-  * Logs 'Toyota' as the value of the 'brand' property
-  * of the object, as changed to by the function.
-  */
- console.log(mycar.brand);
-
- -

The this keyword does not refer to the currently executing function, so you must refer to Function objects by name, even within the function body.

- -

Defining functions

- -

There are several ways to define functions:

- -

The function declaration (function statement)

- -

There is a special syntax for declaring functions (see function statement for details):

- -
function name([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
The function name.
-
- -
-
param
-
The name of an argument to be passed to the function. A function can have up to 255 arguments.
-
- -
-
statements
-
The statements comprising the body of the function.
-
- -

The function expression (function expression)

- -

A function expression is similar to and has the same syntax as a function declaration (see function expression for details). A function expression may be a part of a larger expression. One can define "named" function expressions (where the name of the expression might be used in the call stack for example) or "anonymous" function expressions. Function expressions are not hoisted onto the beginning of the scope, therefore they cannot be used before they appear in the code.

- -
function [name]([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
-
- -
-
param
-
The name of an argument to be passed to the function. A function can have up to 255 arguments.
-
statements
-
The statements comprising the body of the function.
-
- -

Here is an example of an anonymous function expression (the name is not used):

- -
var myFunction = function() {
-    statements
-}
- -

It is also possible to provide a name inside the definition in order to create a named function expression:

- -
var myFunction = function namedFunction(){
-    statements
-}
-
- -

One of the benefit of creating a named function expression is that in case we encounted an error, the stack trace will contain the name of the function, making it easier to find the origin of the error.

- -

As we can see, both example do not start with the function keyword. Statements involving functions which do not start with function are function expressions.

- -

When function are used only once, a common pattern is an IIFE (Immediately Invokable Function Expressions).

- -
(function() {
-    statements
-})();
- -

IIFE are function expression that are invoked as soon as the function is declared.

- -

The generator function declaration (function* statement)

- -

There is a special syntax for generator function declarations (see {{jsxref('Statements/function*', 'function* statement')}} for details):

- -
function* name([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
The function name.
-
- -
-
param
-
The name of an argument to be passed to the function. A function can have up to 255 arguments.
-
- -
-
statements
-
The statements comprising the body of the function.
-
- -

The generator function expression (function* expression)

- -

A generator function expression is similar to and has the same syntax as a generator function declaration (see {{jsxref('Operators/function*', 'function* expression')}} for details):

- -
function* [name]([param[, param[, ... param]]]) {
-   statements
-}
-
- -
-
name
-
The function name. Can be omitted, in which case the function becomes known as an anonymous function.
-
- -
-
param
-
The name of an argument to be passed to the function. A function can have up to 255 arguments.
-
statements
-
The statements comprising the body of the function.
-
- -

The arrow function expression (=>)

- -

An arrow function expression has a shorter syntax and lexically binds its this value (see arrow functions for details):

- -
([param[, param]]) => {
-   statements
-}
-
-param => expression
-
- -
-
param
-
The name of an argument. Zero arguments need to be indicated with ().  For only one argument, the parentheses are not required. (like foo => 1)
-
statements or expression
-
Multiple statements need to be enclosed in brackets. A single expression requires no brackets. The expression is also the implicit return value of the function.
-
- -

The Function constructor

- -
-

Note: Using the Function constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

-
- -

As all other objects, {{jsxref("Function")}} objects can be created using the new operator:

- -
new Function (arg1, arg2, ... argN, functionBody)
-
- -
-
arg1, arg2, ... argN
-
Zero or more names to be used by the function as formal parameters. Each must be a proper JavaScript identifier.
-
- -
-
functionBody
-
A string containing the JavaScript statements comprising the function body.
-
- -

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

- -

The GeneratorFunction constructor

- -
-

Note: GeneratorFunction is not a global object, but could be obtained from generator function instance (see {{jsxref("GeneratorFunction")}} for more detail).

-
- -
-

Note: Using the GeneratorFunction constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

-
- -

As all other objects, {{jsxref("GeneratorFunction")}} objects can be created using the new operator:

- -
new GeneratorFunction (arg1, arg2, ... argN, functionBody)
-
- -
-
arg1, arg2, ... argN
-
Zero or more names to be used by the function as formal argument names. Each must be a string that conforms to the rules for a valid JavaScript identifier or a list of such strings separated with a comma; for example "x", "theValue", or "a,b".
-
- -
-
functionBody
-
A string containing the JavaScript statements comprising the function definition.
-
- -

Invoking the Function constructor as a function (without using the new operator) has the same effect as invoking it as a constructor.

- -

Function parameters

- -

Default parameters

- -

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed. For more details, see default parameters.

- -

Rest parameters

- -

The rest parameter syntax allows to represent an indefinite number of arguments as an array. For more details, see rest parameters.

- -

The arguments object

- -

You can refer to a function's arguments within the function by using the arguments object. See arguments.

- - - -

Defining method functions

- -

Getter and setter functions

- -

You can define getters (accessor methods) and setters (mutator methods) on any standard built-in object or user-defined object that supports the addition of new properties. The syntax for defining getters and setters uses the object literal syntax.

- -
-
get
-
-

Binds an object property to a function that will be called when that property is looked up.

-
-
set
-
Binds an object property to a function to be called when there is an attempt to set that property.
-
- -

Method definition syntax

- -

Starting with ECMAScript 2015, you are able to define own methods in a shorter syntax, similar to the getters and setters. See method definitions for more information.

- -
var obj = {
-  foo() {},
-  bar() {}
-};
- -

Function constructor vs. function declaration vs. function expression

- -

Compare the following:

- -

A function defined with the Function constructor assigned to the variable multiply:

- -
var multiply = new Function('x', 'y', 'return x * y');
- -

A function declaration of a function named multiply:

- -
function multiply(x, y) {
-   return x * y;
-} // there is no semicolon here
-
- -

A function expression of an anonymous function assigned to the variable multiply:

- -
var multiply = function(x, y) {
-   return x * y;
-};
-
- -

A function expression of a function named func_name assigned to the variable multiply:

- -
var multiply = function func_name(x, y) {
-   return x * y;
-};
-
- -

Differences

- -

All do approximately the same thing, with a few subtle differences:

- -

There is a distinction between the function name and the variable the function is assigned to. The function name cannot be changed, while the variable the function is assigned to can be reassigned. The function name can be used only within the function's body. Attempting to use it outside the function's body results in an error (or undefined if the function name was previously declared via a var statement). For example:

- -
var y = function x() {};
-alert(x); // throws an error
-
- -

The function name also appears when the function is serialized via Function's toString method.

- -

On the other hand, the variable the function is assigned to is limited only by its scope, which is guaranteed to include the scope where the function is declared in.

- -

As the 4th example shows, the function name can be different from the variable the function is assigned to. They have no relation to each other. A function declaration also creates a variable with the same name as the function name. Thus, unlike those defined by function expressions, functions defined by function declarations can be accessed by their name in the scope they were defined in:

- -

A function defined by 'new Function' does not have a function name. However, in the SpiderMonkey JavaScript engine, the serialized form of the function shows as if it has the name "anonymous". For example, alert(new Function()) outputs:

- -
function anonymous() {
-}
-
- -

Since the function actually does not have a name, anonymous is not a variable that can be accessed within the function. For example, the following would result in an error:

- -
var foo = new Function("alert(anonymous);");
-foo();
-
- -

Unlike functions defined by function expressions or by the Function constructor, a function defined by a function declaration can be used before the function declaration itself. For example:

- -
foo(); // alerts FOO!
-function foo() {
-   alert('FOO!');
-}
-
- -

A function defined by a function expression inherits the current scope. That is, the function forms a closure. On the other hand, a function defined by a Function constructor does not inherit any scope other than the global scope (which all functions inherit).

- -

Functions defined by function expressions and function declarations are parsed only once, while those defined by the Function constructor are not. That is, the function body string passed to the Function constructor must be parsed each and every time the constructor is called. Although a function expression creates a closure every time, the function body is not reparsed, so function expressions are still faster than "new Function(...)". Therefore the Function constructor should generally be avoided whenever possible.

- -

It should be noted, however, that function expressions and function declarations nested within the function generated by parsing a Function constructor 's string aren't parsed repeatedly. For example:

- -
var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))();
-foo(); // The segment "function() {\n\talert(bar);\n}" of the function body string is not re-parsed.
- -

A function declaration is very easily (and often unintentionally) turned into a function expression. A function declaration ceases to be one when it either:

- - - -
var x = 0;               // source element
-if (x == 0) {            // source element
-   x = 10;               // not a source element
-   function boo() {}     // not a source element
-}
-function foo() {         // source element
-   var y = 20;           // source element
-   function bar() {}     // source element
-   while (y == 10) {     // source element
-      function blah() {} // not a source element
-      y++;               // not a source element
-   }
-}
-
- -

Examples

- -
// function declaration
-function foo() {}
-
-// function expression
-(function bar() {})
-
-// function expression
-x = function hello() {}
-
-
-if (x) {
-   // function expression
-   function world() {}
-}
-
-
-// function declaration
-function a() {
-   // function declaration
-   function b() {}
-   if (0) {
-      // function expression
-      function c() {}
-   }
-}
-
- -

Block-level functions

- -

In strict mode, starting with ES2015, functions inside blocks are now scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.

- -
'use strict';
-
-function f() {
-  return 1;
-}
-
-{
-  function f() {
-    return 2;
-  }
-}
-
-f() === 1; // true
-
-// f() === 2 in non-strict mode
-
- -

Block-level functions in non-strict code

- -

In a word: Don't.

- -

In non-strict code, function declarations inside blocks behave strangely. For example:

- -
if (shouldDefineZero) {
-   function zero() {     // DANGER: compatibility risk
-      console.log("This is zero.");
-   }
-}
-
- -

ES2015 says that if shouldDefineZero is false, then zero should never be defined, since the block never executes. However, it's a new part of the standard. Historically, this was left unspecified, and some browsers would define zero whether the block executed or not.

- -

In strict mode, all browsers that support ES2015 handle this the same way: zero is defined only if shouldDefineZero is true, and only in the scope of the if-block.

- -

A safer way to define functions conditionally is to assign a function expression to a variable:

- -
var zero;
-if (0) {
-   zero = function() {
-      console.log("This is zero.");
-   };
-}
-
- -

Examples

- -

Returning a formatted number

- -

The following function returns a string containing the formatted representation of a number padded with leading zeros.

- -
// This function returns a string padded with leading zeros
-function padZeros(num, totalLen) {
-   var numStr = num.toString();             // Initialize return value as string
-   var numZeros = totalLen - numStr.length; // Calculate no. of zeros
-   for (var i = 1; i <= numZeros; i++) {
-      numStr = "0" + numStr;
-   }
-   return numStr;
-}
-
- -

The following statements call the padZeros function.

- -
var result;
-result = padZeros(42,4); // returns "0042"
-result = padZeros(42,2); // returns "42"
-result = padZeros(5,4);  // returns "0005"
-
- -

Determining whether a function exists

- -

You can determine whether a function exists by using the typeof operator. In the following example, a test is performed to determine if the window object has a property called noFunc that is a function. If so, it is used; otherwise some other action is taken.

- -
 if ('function' == typeof window.noFunc) {
-   // use noFunc()
- } else {
-   // do something else
- }
-
- -

Note that in the if test, a reference to noFunc is used—there are no brackets "()" after the function name so the actual function is not called.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0
{{SpecName('ES5.1', '#sec-13', 'Function Definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}}New: Arrow functions, Generator functions, default parameters, rest parameters.
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Generator functions39{{CompatGeckoDesktop("26.0")}}{{CompatUnknown}}26{{CompatUnknown}}
Arrow functions{{CompatChrome(45.0)}}{{CompatGeckoDesktop("22.0")}}{{CompatNo}}{{CompatOpera(32)}}10
Block-level functions{{CompatUnknown}}{{CompatGeckoDesktop("46.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Generator functions{{CompatUnknown}}39{{CompatGeckoMobile("26.0")}}{{CompatUnknown}}26{{CompatUnknown}}
Arrow functions{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("22.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
Block-level functions{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("46.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

See also

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/concat/index.html b/files/vi/web/javascript/reference/global_objects/array/concat/index.html deleted file mode 100644 index f19a1b981b..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/concat/index.html +++ /dev/null @@ -1,150 +0,0 @@ ---- -title: Array.prototype.concat() -slug: Web/JavaScript/Reference/Global_Objects/Array/concat -translation_of: Web/JavaScript/Reference/Global_Objects/Array/concat ---- -
{{JSRef}}
- -

Phương thức concat() dùng để kết nối 2 hay nhiều mảng với nhau. Phương thức này  không làm thay đổi các mảng đã có mà thay vào đó sẽ trả về 1 mảng mới.

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

Cú pháp

- -
var newArray = oldArray.concat(value1[, value2[, ...[, valueN]]])
- -

Tham số

- -
-
valueN
-
Các giá trị hay mảng dùng để nối lại với nhau trong mảng mới .
-
- -

Giá trị trả về

- -

Một mảng {{jsxref("Array")}} mới.

- -

Mô tả

- -

Phương thức concat tạo ra 1 mảng mới bao gồm các phần tử trong đối tượng mà nó được gọi thực thi, và theo thứ tự lần lượt, với mỗi tham số truyền vào là các phần tử của tham số đó (nếu tham số truyền vào là 1 mảng) hoặc là chính tham số đó (nếu tham số truyền vào không  phải là 1 mảng). Phương thức này sẽ không thực thi 1 cách đệ quy cho các tham số là mảng lồng nhau.

- -

Phương thức concat không thay đổi this (mảng được gọi thực thi)  hay bất cứ mảng được truyền vào làm tham số mà thay vào đó nó sẽ trả về 1 bản sao tham chiếu (shallow copy) bao gồm các bản sao của cùng 1 phần tử được kết hợp từ các mảng ban đầu. Các phần từ của mảng ban đầu được sao chép vào mảng mới như sau: 

- - - -
-

Chú ý: Việc ghép nối các mảng hay giá trị sẽ không "đụng chạm" tới các giá trị ban đầu. Hơn nữa, bất cứ thao tác nào trên mảng trả về (ngoại trừ các thao tác trên các phần từ là tham chiếu đối tượng) sẽ không ảnh hưởng tới các mảng ban đầu, và ngược lại.

-
- -

Ví dụ

- -

Nối 2 mảng

- -

Đoạn mã dưới đây sẽ nối 2 mảng lại với nhau:

- -
var alpha = ['a', 'b', 'c'];
-var numeric = [1, 2, 3];
-
-alpha.concat(numeric);
-// result in ['a', 'b', 'c', 1, 2, 3]
-
- -

Nối 3 mảng

- -

Đoạn mã dưới đây sẽ nối 3 mảng lại với nhau

- -
var num1 = [1, 2, 3],
-    num2 = [4, 5, 6],
-    num3 = [7, 8, 9];
-
-var nums = num1.concat(num2, num3);
-
-console.log(nums);
-// results in [1, 2, 3, 4, 5, 6, 7, 8, 9]
-
- -

Nối các giá trị vào 1 mảng

- -

Đoạn mã sau đây sẽ nối 3 giá trị vào 1 mảng:

- -
var alpha = ['a', 'b', 'c'];
-
-var alphaNumeric = alpha.concat(1, [2, 3]);
-
-console.log(alphaNumeric);
-// results in ['a', 'b', 'c', 1, 2, 3]
-
- -

Nối mảng lồng nhau

- -

Đoạn mã sau đây sẽ nối các mảng lồng nhau và thể hiện sự lưu trữ tham chiếu:

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

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES3')}}{{Spec2('ES3')}}Định nghĩa lần đầu. Hiện thực trong JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.4', 'Array.prototype.concat')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.concat', 'Array.prototype.concat')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.concat', 'Array.prototype.concat')}}{{Spec2('ESDraft')}} 
- -

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

- -
- - -

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

-
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/copywithin/index.html b/files/vi/web/javascript/reference/global_objects/array/copywithin/index.html deleted file mode 100644 index fd216cbc54..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/copywithin/index.html +++ /dev/null @@ -1,170 +0,0 @@ ---- -title: Array.prototype.copyWithin() -slug: Web/JavaScript/Reference/Global_Objects/Array/copyWithin -translation_of: Web/JavaScript/Reference/Global_Objects/Array/copyWithin ---- -
{{JSRef}}
- -

 copyWithin()  là một phương thức sao chép cạn một phần của mảng tới một vị trí khác trong mảng đó và trả về giá trị mà không thay đổi độ dài của mảng

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

Cú pháp

- -
arr.copyWithin(target[, start[, end]])
-
- -

Parameters

- -
-
target
-
Zero-based index at which to copy the sequence to. If negative, target will be counted from the end.
-
If target is at or greater than arr.length, nothing will be copied. If target is positioned after start, the copied sequence will be trimmed to fit arr.length.
-
start {{optional_inline}}
-
Zero-based index at which to start copying elements from. If negative, start will be counted from the end.
-
If start is omitted, copyWithin will copy from index 0
-
end {{optional_inline}}
-
Zero-based index at which to end copying elements from. copyWithin copies up to but not including end. If negative, end will be counted from the end.
-
If end is omitted, copyWithin will copy until the last index (default to arr.length).
-
- -

Return value

- -

The modified array.

- -

Description

- -

The copyWithin works like C and C++'s memmove, and is a high-performance method to shift the data of an {{jsxref("Array")}}. This especially applies to the {{jsxref("TypedArray/copyWithin", "TypedArray")}} method of the same name. The sequence is copied and pasted as one operation; pasted sequence will have the copied values even when the copy and paste region overlap.

- -

The copyWithin function is intentionally generic, it does not require that its this value be an {{jsxref("Array")}} object.

- -

The copyWithin method is a mutable method. It does not alter the length of this, but it will change its content and create new properties, if necessary.

- -

Polyfill

- -
if (!Array.prototype.copyWithin) {
-  Object.defineProperty(Array.prototype, 'copyWithin', {
-    value: function(target, start/*, end*/) {
-    // Steps 1-2.
-    if (this == null) {
-      throw new TypeError('this is null or not defined');
-    }
-
-    var O = Object(this);
-
-    // Steps 3-5.
-    var len = O.length >>> 0;
-
-    // Steps 6-8.
-    var relativeTarget = target >> 0;
-
-    var to = relativeTarget < 0 ?
-      Math.max(len + relativeTarget, 0) :
-      Math.min(relativeTarget, len);
-
-    // Steps 9-11.
-    var relativeStart = start >> 0;
-
-    var from = relativeStart < 0 ?
-      Math.max(len + relativeStart, 0) :
-      Math.min(relativeStart, len);
-
-    // Steps 12-14.
-    var end = arguments[2];
-    var relativeEnd = end === undefined ? len : end >> 0;
-
-    var final = relativeEnd < 0 ?
-      Math.max(len + relativeEnd, 0) :
-      Math.min(relativeEnd, len);
-
-    // Step 15.
-    var count = Math.min(final - from, len - to);
-
-    // Steps 16-17.
-    var direction = 1;
-
-    if (from < to && to < (from + count)) {
-      direction = -1;
-      from += count - 1;
-      to += count - 1;
-    }
-
-    // Step 18.
-    while (count > 0) {
-      if (from in O) {
-        O[to] = O[from];
-      } else {
-        delete O[to];
-      }
-
-      from += direction;
-      to += direction;
-      count--;
-    }
-
-    // Step 19.
-    return O;
-  },
-  configurable: true,
-  writable: true
-  });
-}
- -

Examples

- -

Using copyWithin

- -
[1, 2, 3, 4, 5].copyWithin(-2)
-// [1, 2, 3, 1, 2]
-
-[1, 2, 3, 4, 5].copyWithin(0, 3)
-// [4, 5, 3, 4, 5]
-
-[1, 2, 3, 4, 5].copyWithin(0, 3, 4)
-// [4, 2, 3, 4, 5]
-
-[1, 2, 3, 4, 5].copyWithin(-2, -3, -1)
-// [1, 2, 3, 3, 4]
-
-[].copyWithin.call({length: 5, 3: 1}, 0, 3)
-// {0: 1, 3: 1, length: 5}
-
-// ES2015 Typed Arrays are subclasses of Array
-var i32a = new Int32Array([1, 2, 3, 4, 5])
-
-i32a.copyWithin(0, 2)
-// Int32Array [3, 4, 5, 4, 5]
-
-// On platforms that are not yet ES2015 compliant:
-[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4);
-// Int32Array [4, 2, 3, 4, 5]
-
- -

Specifications

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

Browser compatibility

- -
- - -

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

-
- -

See also

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/entries/index.html b/files/vi/web/javascript/reference/global_objects/array/entries/index.html deleted file mode 100644 index 6be2131071..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/entries/index.html +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: Array.prototype.entries() -slug: Web/JavaScript/Reference/Global_Objects/Array/entries -translation_of: Web/JavaScript/Reference/Global_Objects/Array/entries ---- -
{{JSRef}}
- -

Phương thức entries() trả về một mảng đối tượng Array Iterator chứa cặp key/value cho mỗi chỉ mục trong mảng.

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

Syntax

- -
array.entries()
- -

Return value

- -

Một {{jsxref("Array")}} đối tượng iterator.

- -

Examples

- -

Iterating with index and element

- -
const a = ['a', 'b', 'c'];
-
-for (const [index, element] of a.entries())
-  console.log(index, element);
-
-// 0 'a'
-// 1 'b'
-// 2 'c'
-
- -

Using a for…of loop

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

Specifications

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

Browser compatibility

- -
- - -

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

-
- -

See also

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/every/index.html b/files/vi/web/javascript/reference/global_objects/array/every/index.html deleted file mode 100644 index efeaa2deca..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/every/index.html +++ /dev/null @@ -1,236 +0,0 @@ ---- -title: Array.prototype.every() -slug: Web/JavaScript/Reference/Global_Objects/Array/every -translation_of: Web/JavaScript/Reference/Global_Objects/Array/every ---- -
{{JSRef}}
- -

Phương thức every() sẽ kiểm tra xem mọi phần tử bên trong một array được truyền vào có vượt qua được bài kiểm tra khi thực hiện với function được cung cấp không. every() sẽ return về một kết quả Boolean.

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

Cú pháp

- -
arr.every(callback(element[, index[, array]])[, thisArg])
- -

Parameters

- -
-
callback
-
Một function với chức năng là kiểm tra từng phần tử trong mảng được cung cấp cho every(), nhận vào 3 đối số: -
-
element
-
Là phần tử hiện tại của mảng đang được function xử lý.
-
index {{Optional_inline}}
-
Index của phần tử trên.
-
array {{Optional_inline}}
-
Mảng mà every() gọi.
-
-
-
thisArg {{Optional_inline}}
-
A value to use as this when executing callback.
-
- -

Return value

- -

true if the callback function returns a truthy value for every array element. Otherwise, false.

- -

Description

- -

The every method executes the provided callback function once for each element present in the array until it finds the one where callback returns a falsy value. If such an element is found, the every method immediately returns false. Otherwise, if callback returns a truthy value for all elements, every returns true.

- -
-

Caution: Calling this method on an empty array will return true for any condition!

-
- -

callback is invoked only for array indexes which have assigned values. It is not invoked for indexes which have been deleted, or which have never been assigned values.

- -

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

- -

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

- -

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

- -

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

- -

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

- -

Polyfill

- -

every was added to the ECMA-262 standard in the 5th edition, and it may not be present in other implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of every in implementations which do not natively support it.

- -

This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming Object and TypeError have their original values, and that callbackfn.call evaluates to the original value of {{jsxref("Function.prototype.call")}}.

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

Examples

- -

Testing size of all array elements

- -

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

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

Using arrow functions

- -

Arrow functions provide a shorter syntax for the same test.

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

Affecting Initial Array (modifying, appending, and deleting)

- -

The following examples tests the behaviour of the every method when the array is modified.

- -
// ---------------
-// Modifying items
-// ---------------
-let arr = [1, 2, 3, 4];
-arr.every( (elem, index, arr) => {
-  arr[index+1] -= 1
-  console.log(`[${arr}][${index}] -> ${elem}`)
-  return elem < 2
-})
-
-// Loop runs for 3 iterations, but would
-// have run 2 iterations without any modification
-//
-// 1st iteration: [1,1,3,4][0] -> 1
-// 2nd iteration: [1,1,2,4][1] -> 1
-// 3rd iteration: [1,1,2,3][2] -> 2
-
-// ---------------
-// Appending items
-// ---------------
-arr = [1, 2, 3];
-arr.every( (elem, index, arr) => {
-  arr.push('new')
-  console.log(`[${arr}][${index}] -> ${elem}`)
-  return elem < 4
-})
-
-// Loop runs for 3 iterations, even after appending new items
-//
-// 1st iteration: [1, 2, 3, new][0] -> 1
-// 2nd iteration: [1, 2, 3, new, new][1] -> 2
-// 3rd iteration: [1, 2, 3, new, new, new][2] -> 3
-
-// ---------------
-// Deleting items
-// ---------------
-arr = [1, 2, 3, 4];
-arr.every( (elem, index, arr) => {
-  arr.pop()
-  console.log(`[${arr}][${index}] -> ${elem}`)
-  return elem < 4
-})
-
-// Loop runs for 2 iterations only, as the remaining
-// items are `pop()`ed off
-//
-// 1st iteration: [1,2,3][0] -> 1
-// 2nd iteration: [1,2][1] -> 2
- -

Specifications

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

Browser compatibility

- -
- - -

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

-
- -

See also

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/fill/index.html b/files/vi/web/javascript/reference/global_objects/array/fill/index.html deleted file mode 100644 index e7e8201c46..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/fill/index.html +++ /dev/null @@ -1,149 +0,0 @@ ---- -title: Array.prototype.fill() -slug: Web/JavaScript/Reference/Global_Objects/Array/fill -translation_of: Web/JavaScript/Reference/Global_Objects/Array/fill ---- -
{{JSRef}}
- -

Phương thức fill() điền (sửa đổi) tất cả các phần tử của một mảng từ một chỉ mục bắt đầu (số không mặc định) đến một chỉ mục kết thúc (độ dài mảng mặc định) với một giá trị tĩnh. Nó trả về mảng đã sửa đổi

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

Syntax

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

Parameters

- -
-
value
-
Value to fill an array.
-
start {{optional_inline}}
-
Start index, defaults to 0.
-
end {{optional_inline}}
-
End index, defaults to this.length.
-
- -

Return value

- -

The modified array.

- -

Description

- -

The fill method takes up to three arguments value, start and end. The start and end arguments are optional with default values of 0 and the length of the this object.

- -

If start is negative, it is treated as length+start where length is the length of the array. If end is negative, it is treated as length+end.

- -

fill is intentionally generic, it does not require that its this value be an Array object.

- -

fill is a mutable method, it will change this object itself, and return it, not just return a copy of it.

- -

When fill gets passed an object, it will copy the reference and fill the array with references to that object.

- -

Examples

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

Polyfill

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

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

- -

Specifications

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

Browser compatibility

- -
- - -

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

-
- -

See also

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/filter/index.html b/files/vi/web/javascript/reference/global_objects/array/filter/index.html deleted file mode 100644 index 900c22a1ac..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/filter/index.html +++ /dev/null @@ -1,232 +0,0 @@ ---- -title: Array.prototype.filter() -slug: Web/JavaScript/Reference/Global_Objects/Array/filter -translation_of: Web/JavaScript/Reference/Global_Objects/Array/filter ---- -
{{JSRef}}
- -

Phương thức filter() dùng để tạo một mảng mới với tất cả các phần tử thỏa điều kiện của một hàm test.

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

Cú pháp

- -
var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])
- -

Tham số

- -
-
callback
-
Đây là hàm thử, dùng để kiểm tra từng phần tử của mảng.  Trả về true để giữ lại phần tử, hoặc false để loại nó ra. Nó được gọi với ba tham số:
-
-
-
element
-
Phần tử đang được xử lý trong mảng.
-
index{{optional_inline}}
-
Chỉ mục (index) của phần tử đang được xử lý.
-
array{{optional_inline}}
-
Mảng nguồn mà hàm filter đang xử lý.
-
-
-
thisArg {{optional_inline}}
-
Không bắt buộc. Giá trị của this bên trong hàm callback.
-
- -

Giá trị trả về

- -

Một mảng mới với các phần tử đã thỏa điều kiện của hàm test. Nếu không có phần tử nào thỏa điều kiện, một mảng rỗng sẽ được trả về.

- -

Mô tả

- -

filter() sẽ thực thi hàm callback trên từng phần tử của mảng, và xây dựng một mảng mới với các phần tử mà giá trị trả về của callback nếu ép kiểu sẽ mang giá trị true. callback chỉ được thực thi tại những chỉ mục (index) của mảng mà chúng được gán giá trị; nó không được thực thi tại chỉ mục đã bị xóa hoặc chưa từng được gán giá trị. Những phần tử không thỏa điều kiện tại hàm thử callback sẽ bị bỏ qua, không được cho vào mảng mới.

- -

callback được gọi với ba tham số:

- -
    -
  1. giá trị của phần tử
  2. -
  3. chỉ mục (index) của phần tử
  4. -
  5. mảng ban đầu mà hàm thử đang được gọi lên
  6. -
- -

Nếu tham số thisArg được truyền cho hàm filter, nó sẽ được thay vào giá trị của từ khóa this trong hàm callback. Nếu không, giá trị undefined sẽ được dùng cho this. Tóm lại, giá trị của từ khóa this trong hàm callback được xác định tuân theo các quy tắc thông thường để xác định this trong một hàm.

- -

filter() không làm thay đổi mảng mà nó được gọi.

- -

Các phần tử được filter() chạy qua được xác định từ đầu trước khi callback được gọi lần đầu tiên. Những phần tử mới được thêm vào sau khi filter() bắt đầu chạy sẽ không được truyền vào callback. Trong lúc filter() đang chạy, nếu những phần tử hiện tại của mảng bị thay đổi, thì giá trị của chúng khi được truyền cho callback  là giá trị tại thời điểm filter() chạy qua; những phần tử đã xóa sẽ bị bỏ qua.

- -

Ví dụ

- -

Lọc bỏ các giá trị nhỏ

- -

Ví dụ sau sẽ dùng filter() để tạo một mảng lọc không có các phần tử nào nhỏ hơn 10.

- -
function isBigEnough(value) {
-  return value >= 10;
-}
-
-var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
-// filtered is [12, 130, 44]
-
- -

Lọc các giá trị không hợp lệ khỏi JSON

- -

Ví dụ sau sẽ dùng hàm filter() để lọc lại các phần tử của JSON chỉ chứa id có giá trị số và khác 0.

- -
var arr = [
-  { id: 15 },
-  { id: -1 },
-  { id: 0 },
-  { id: 3 },
-  { id: 12.2 },
-  { },
-  { id: null },
-  { id: NaN },
-  { id: 'undefined' }
-];
-
-var invalidEntries = 0;
-
-function isNumber(obj) {
-  return obj !== undefined && typeof(obj) === 'number' && !isNaN(obj);
-}
-
-function filterByID(item) {
-  if (isNumber(item.id) && item.id !== 0) {
-    return true;
-  }
-  invalidEntries++;
-  return false;
-}
-
-var arrByID = arr.filter(filterByID);
-
-console.log('Filtered Array\n', arrByID);
-// Filtered Array
-// [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }]
-
-console.log('Number of Invalid Entries = ', invalidEntries);
-// Number of Invalid Entries = 5
-
- -

Tìm kiếm trong mảng

- -

Ví dụ sau dùng filter() để lọc ra phần tử có nội dung thỏa chuỗi tìm kiếm

- -
var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
-
-/**
- * Array filters items based on search criteria (query)
- */
-function filterItems(query) {
-  return fruits.filter(function(el) {
-      return el.toLowerCase().indexOf(query.toLowerCase()) > -1;
-  })
-}
-
-console.log(filterItems('ap')); // ['apple', 'grapes']
-console.log(filterItems('an')); // ['banana', 'mango', 'orange']
- -

Ví dụ ở trên với ES2015

- -
const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
-
-/**
- * Array filters items based on search criteria (query)
- */
-const filterItems = (query) => {
-  return fruits.filter((el) =>
-    el.toLowerCase().indexOf(query.toLowerCase()) > -1
-  );
-}
-
-console.log(filterItems('ap')); // ['apple', 'grapes']
-console.log(filterItems('an')); // ['banana', 'mango', 'orange']
-
-
- -

Polyfill

- -

filter() chỉ được thêm vào đặc tả ECMA-262 phiên bản thứ 5; cho nên nó có thể không tồn tại trong một số hiện thực (implementation) của đặc tả. Bạn có thể xoay sở bằng cách thêm vào đoạn code bên dưới vào đầu script của bạn, cho phép sử dụng filter() tại những nơi mà nó không được hỗ trợ sẵn. Giải thuật trong hàm polyfill này chính xác với đặc tả trong ECMA-262, 5th edition, với yêu cầu fn.call trả về giá trị ban đầu của {{jsxref("Function.prototype.bind()")}}, và {{jsxref("Array.prototype.push()")}} không bị thay đổi.

- -
if (!Array.prototype.filter){
-  Array.prototype.filter = function(func, thisArg) {
-    'use strict';
-    if ( ! ((typeof func === 'Function' || typeof func === 'function') && this) )
-        throw new TypeError();
-
-    var len = this.length >>> 0,
-        res = new Array(len), // preallocate array
-        t = this, c = 0, i = -1;
-    if (thisArg === undefined){
-      while (++i !== len){
-        // checks to see if the key was set
-        if (i in this){
-          if (func(t[i], i, t)){
-            res[c++] = t[i];
-          }
-        }
-      }
-    }
-    else{
-      while (++i !== len){
-        // checks to see if the key was set
-        if (i in this){
-          if (func.call(thisArg, t[i], i, t)){
-            res[c++] = t[i];
-          }
-        }
-      }
-    }
-
-    res.length = c; // shrink down array to proper size
-    return res;
-  };
-}
- -

 

- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES5.1', '#sec-15.4.4.20', 'Array.prototype.filter')}}{{Spec2('ES5.1')}}Định nghĩa lần đầu. Được hiện thực trong JavaScript 1.6.
{{SpecName('ES2015', '#sec-array.prototype.filter', 'Array.prototype.filter')}}{{Spec2('ES2015')}} 
{{SpecName('ESDraft', '#sec-array.prototype.filter', 'Array.prototype.filter')}}{{Spec2('ESDraft')}} 
- -

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

- -
- - -

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

-
- -

Tương tự

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

Phương thức find() sẽ trả về giá trị đầu tiên tìm thấy ở trong mảng được cung cấp. Hoặc có thể trả về {{jsxref("undefined")}} .

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

Xem thêm phương thức {{jsxref("Array.findIndex", "findIndex()")}} , sẽ trả về index của phần tử tìm thấy trong mảng thay vì giá trị của nó.

- -

Nếu bạn muốn tìm vị trí của phần tử hoặc tìm phần tử đó có tồn tại trong mảng hay không, hãy thử sử dụng  {{jsxref("Array.prototype.indexOf()")}} or {{jsxref("Array.prototype.includes()")}}.

- -

Cú Pháp

- -
arr.find(callback(element[, index[, array]])[, thisArg])
- -

Parameters ( thông số đầu vào )

- -
-
callback
-
Hàm thực thi với mỗi giá trị trong mảng, chuyền vào 3 giá trị : -
-
element
-
Phần tử hiện tại đang được xử lý trong mảng.
-
index {{optional_inline}}
-
Thứ tự của phần tử hiện tại đang được xử lý trong mảng..
-
array {{optional_inline}}
-
Mảng được gọi.
-
-
-
thisArg {{optional_inline}}
-
Đối tượng tùy chọn để sử dụng như thế này khi thực hiện callback.
-
- -

Return value ( giá trị trả về )

- -

Giá trị ( value ) của phần tử đầu tiên ( first element ) trong mảng thỏa mãn chức năng kiểm tra được cung cấp. Nếu không, sẽ trả về {{jsxref("undefined")}}.

- -

Mô Tả

- -

Phương thức find thực thi hàm  callback với mỗi giá trị trong mảng cho đến khi tìm được giá trị mà hàm callback trả về giá trị. Nếu phần tử đó được tìm thấy, phương thức find sẽ trả về giá trị của phần tử đó. Nếu không tìm thấy, find sẽ trả về {{jsxref("undefined")}}. callback được gọi cho mọi index có trong mảng từ 0 đếnlength - 1 và cho tất cả các indexes, không chỉ những giá trị đã được gán. Điều này chỉ ra rằng nó có thể kém hiệu quả hơn so với các phương thức khác chỉ truy cập các indexes có giá trị được gán.

- -

callback được gọi với ba arguments: giá trị của phần tử ( the value of the element ), biến đếm của phần tử ( the index of the element ) và đối tượng mảng cần tìm ( the Array object being traversed ).

- -

Nếu thisArg tham số ( parameter ) cung cấp cho phương thức find, nó sẽ được sử dụng như là giá trị this cho mỗi lần gọi callback. Nếu không được cung cấp tham số, thì {{jsxref("undefined")}} sẽ được thay thế.

- -

Phương thức find sẽ không làm thay đổi mảng mà nó được gọi hoặc sử dụng.

- -

Phạm vi của các phần tử được xử lý bởi find sẽ được gán trước ghi gọi hàm callback. Vì thế, callback sẽ không truy cập các phần tử được gắn vào mảng sau khi phương thức find được bắt đầu. Các phần tử bị xóa vẫn có thể truy cập được.

- -

Ví Dụ

- -

Tìm một đối tượng trong một mảng bằng một trong các thuộc tính

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

Sử dụng arrow function ( ES2015 )

- -
const inventory = [
-    {name: 'apples', quantity: 2},
-    {name: 'bananas', quantity: 0},
-    {name: 'cherries', quantity: 5}
-];
-
-const result = inventory.find( fruit => fruit.name === 'cherries' );
-
-console.log(result) // { name: 'cherries', quantity: 5 }
- -

Tìm số nguyên tố trong mảng

- -

Theo ví dụ sau đây tìm thấy một phần tử trong mảng là số nguyên tố (hoặc sẽ trả về {{jsxref("undefined")}} nếu trong mảng không có số nguyên tố nào).

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

Ví dụ sau đây cho thấy các phần tử không tồn tại và bị xóa vẫn được truy cập và giá trị được chuyển cho callback lại là giá trị của chúng khi được truy cập.

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

Polyfill

- -

Phương pháp này đã được thêm vào ECMAScript 2015 và có thể không có sẵn trong tất cả các phiên bản JavaScript. Tuy nhiên, bạn có thể sử dụng Array.prototype.find với cú pháp :

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

Đặc Điểm

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

Tính Tương Thích Với Trình Duyệt Web

- -
- - -

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

-
- -

Những Phương Thức Liên Quan

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/findindex/index.html b/files/vi/web/javascript/reference/global_objects/array/findindex/index.html deleted file mode 100644 index 3c8d822f07..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/findindex/index.html +++ /dev/null @@ -1,207 +0,0 @@ ---- -title: Array.prototype.findIndex() -slug: Web/JavaScript/Reference/Global_Objects/Array/findIndex -translation_of: Web/JavaScript/Reference/Global_Objects/Array/findIndex ---- -
{{JSRef}}
- -

Phương thức findIndex() trả về chỉ số (index) của phần tử đầu tiên trong mảng thỏa mãn hàm truyền vào. Nếu không phần tử nào thỏa mãn, phương thức trả lại -1.

- -
function isBigEnough(element) {
-  return element >= 15;
-}
-
-[12, 5, 8, 130, 44].findIndex(isBigEnough); // Trả về 3, phần tử thứ 4.
- -

Xem thêm phương thức {{jsxref("Array.find", "find()")}}, trả về giá trị (value) của phần tử được tìm thấy thay vì chỉ số.

- -

Cú pháp

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

Tham số

- -
-
callback
-
Hàm kiểm tra, được thực thi cho mỗi phần tử của mảng, có thể chứa 3 tham số: -
-
element
-
Phần tử đang xét.
-
index
-
Chỉ số của phần tử đang xét.
-
array
-
Mảng được gọi.
-
-
-
thisArg
-
Optional. Object to use as this when executing callback.
-
- -

Giá trị trả về

- -

Một chỉ số của mảng nếu tìm được phần tử đầu tiên thỏa mãn hàm kiểm tra; otherwise, -1.

- -

Mô tả

- -

Phương thức findIndex thực thi hàm callback từng lần cho toàn bộ chỉ số mảng từ  0..length-1 (bao gồm hai nút) trong mảng cho tới khi tìm thấy chỉ số mà phần tử tại đó làm cho callback trả về một giá trị đúng (a value that coerces to true). Nếu một phần tử được tìm thấy, findIndex lập tức trả về chỉ số của phần tử này. Nếu hàm callback luôn nhận giá trị không đúng hoặc số phần tử của mảng bằng 0, findIndex trả về -1. Không giống như cách phương thức về mảng khác như Array#some, trong mảng thưa thớt hàm callback được gọi là ngay cả đối với các chỉ mục của mục không có trong mảng đó.

- -

callback được gọi với 3 đối số: giá trị của phần tử, chỉ số của phần tử, và mảng đang được xét.

- -

Nếu tham số thisArg được đưa vào findIndex, Nó sẽ được sử dụng như là this cho mỗi lần gọi callback. Nếu nó không được đưa vào, thì {{jsxref("undefined")}} sẽ được sử dụng.

- -

findIndex không làm thay đổi mảng mà nó được gọi.

- -

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

- -

Ví dụ

- -

Tìm chỉ số của một số nguyên tố trong mảng

- -

Ví dụ dưới đây tìm chỉ số của một phần tử trong mảng mà là số nguyên tố (trả về -1 nếu không tìm thấy).

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

Polyfill

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

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

- -

Các thông số

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

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

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerEdgeOperaSafari
Basic support{{CompatChrome(45.0)}}{{CompatGeckoDesktop("25.0")}}{{CompatNo}}YesYes{{CompatSafari("7.1")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatGeckoMobile("25.0")}}{{CompatNo}}{{CompatNo}}8.0
-
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/flat/index.html b/files/vi/web/javascript/reference/global_objects/array/flat/index.html deleted file mode 100644 index 065a92a7a5..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/flat/index.html +++ /dev/null @@ -1,179 +0,0 @@ ---- -title: Array.prototype.flat() -slug: Web/JavaScript/Reference/Global_Objects/Array/flat -tags: - - Array - - JavaScript - - Method - - Prototype - - Reference - - flat -translation_of: Web/JavaScript/Reference/Global_Objects/Array/flat ---- -
{{JSRef}}
- -
Phương thức flat()  trả về một mảng mới. Trong đó, tất cả các phần tử của mảng con được gán ngược vào nó bằng  cách đệ quy lên đến độ sâu đã chỉ định.
- - - -

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

- - - -

Syntax

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

Parameters

- -
-
depth {{optional_inline}}
-
Chỉ định độ sâu của mảng kết quả cuối cùng. Mặc định là 1
-
- -

Return value

- -

Một mảng mới với các phần tử của mảng con được nối với nó.

- -

Alternatives

- -

reduce and concat

- -
const arr = [1, 2, [3, 4]];
-
-// Trả về mảng chỉ có 1 level
-arr.flat();
-
-// Nó ngang với việc sử dụng reduce
-arr.reduce((acc, val) => acc.concat(val), []);
-// [1, 2, 3, 4]
-
-// hoặc decomposition syntax
-const flattened = arr => [].concat(...arr);
-
- -

reduce + concat + isArray + recursivity

- -
const arr = [1, 2, [3, 4, [5, 6]]];
-
-// ?Sử dụng reduce, concat và deep level
-function flatDeep(arr, d = 1) {
-   return d > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatDeep(val, d - 1) : val), [])
-                : arr.slice();
-};
-
-flatDeep(arr, Infinity);
-// [1, 2, 3, 4, 5, 6]
-
- -

Use a stack

- -
// Sử dụng stack để đệ quy không cần báo deep level
-
-function flatten(input) {
-  const stack = [...input];
-  const res = [];
-  while(stack.length) {
-    // Lấy gía trị ra khỏi stack
-    const next = stack.pop();
-    if(Array.isArray(next)) {
-      // Gán trở lại arry, không thay đổi giá trị của item đó
-      stack.push(...next);
-    } else {
-      res.push(next);
-    }
-  }
-  // Đảo ngược array để trả về đúng order ban đầu
-  return res.reverse();
-}
-
-const arr = [1, 2, [3, 4, [5, 6]]];
-flatten(arr);
-// [1, 2, 3, 4, 5, 6]
-
- -

Use Generator function

- -
function* flatten(array, depth) {
-    if(depth === undefined) {
-      depth = 1;
-    }
-    for(const item of array) {
-        if(Array.isArray(item) && depth > 0) {
-          yield* flatten(item, depth - 1);
-        } else {
-          yield item;
-        }
-    }
-}
-
-const arr = [1, 2, [3, 4, [5, 6]]];
-const flattened = [...flatten(arr, Infinity)];
-// [1, 2, 3, 4, 5, 6]
-
- - - -

Examples

- -

Flattening nested arrays

- -
const arr1 = [1, 2, [3, 4]];
-arr1.flat();
-// [1, 2, 3, 4]
-
-const arr2 = [1, 2, [3, 4, [5, 6]]];
-arr2.flat();
-// [1, 2, 3, 4, [5, 6]]
-
-const arr3 = [1, 2, [3, 4, [5, 6]]];
-arr3.flat(2);
-// [1, 2, 3, 4, 5, 6]
-
-const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
-arr4.flat(Infinity);
-// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
-
- -

Flattening and array holes

- -

The flat method removes empty slots in arrays:

- -
const arr5 = [1, 2, , 4, 5];
-arr5.flat();
-// [1, 2, 4, 5]
-
- -

Specifications

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

Browser compatibility

- -
- - -

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

-
- -

See also

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/foreach/index.html b/files/vi/web/javascript/reference/global_objects/array/foreach/index.html deleted file mode 100644 index 6121f40a83..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/foreach/index.html +++ /dev/null @@ -1,303 +0,0 @@ ---- -title: Array.prototype.forEach() -slug: Web/JavaScript/Reference/Global_Objects/Array/forEach -translation_of: Web/JavaScript/Reference/Global_Objects/Array/forEach ---- -
{{JSRef}}
- -

Phương thức forEach() sẽ thực thi một hàm khi duyệt qua từng phần tử của mảng.

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

Cú pháp

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

Parameters

- -
-
callback
-
Hàm sẽ thực thi lên từng phần tử của mảng được gọi, hàm này nhận 3 tham số: -
-
currentValue{{optional_inline}}
-
Giá trị của phần tử đang được duyệt.
-
index{{optional_inline}}
-
Chỉ mục của phần tử đang được duyệt.
-
array{{optional_inline}}
-
Mảng mà hàm forEach() đang duyệt.
-
-
-
thisArg {{Optional_inline}}
-
-

Giá trị được gán cho từ khóa this bên trong hàm callback khi được thực thi.

-
-
- -

Giá trị trả về

- -

{{jsxref("undefined")}}.

- -

Mô tả chi tiết

- -

forEach() thực thi hàm callback trong lúc duyệt tới từng phần tử của mảng theo thứ tự tăng dần. Nó sẽ không được gọi cho vị trí index đã bị xóa hoặc không được khởi tạo (đối với mảng thưa - sparse arrays).

- -

callback được gọi với 3 tham số:

- - - -

Nếu tham số thisArg được truyền vào cho forEach(), nó sẽ được dùng cho từ khóa this trong hàm callback. Nếu không, giá trị {{jsxref("undefined")}} sẽ được dùng cho từ khóa this. Tóm lại, giá trị của từ khóa this trong hàm callback được xác định tuân theo các quy tắc thông thường để xác định this trong một hàm.

- -

Khoảng các phần tử được xử lý bởi forEach() được thiết lập trước lần gọi đầu tiên của callback. Phần tử được thêm vào mảng sau khi gọi forEach() sẽ không được callback bắt gặp. Nếu giá trị của các phần tử sẵn có trong mảng thay đổi, thì giá trị truyền vào callback sẽ là giá trị lúc forEach() gặp chúng; phần tử bị xoá trước khi bắt gặp sẽ không tính. Nếu phần tử đã gặp rồi bị loại đi (ví dụ dùng {{jsxref("Array.prototype.shift()", "shift()")}}) trong quá trình lặp, các phần tử sau sẽ bị bỏ qua - xem ví dụ phía dưới.

- -

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

- -

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

- -
-

Khác với cú pháp lặp truyền thống, không có cách nào để ngừng vòng lặp forEach ngoài việc ném ra một ngoại lệ. Nếu vì một mục đích nào đó mà bạn cần ngừng vòng lặp thì nên dùng cách khác thay vì dùng forEach

- -

Một số cách có thể dùng trong trường hợp đó:

- - - -

Một số hàm khác trên kiểu mảng: {{jsxref("Array.prototype.every()", "every()")}}, {{jsxref("Array.prototype.some()", "some()")}}, {{jsxref("Array.prototype.find()", "find()")}}, and {{jsxref("Array.prototype.findIndex()", "findIndex()")}} test the array elements with a predicate returning a truthy value to determine if further iteration is required.

-
- -

Ví dụ

- -

Converting a for loop to forEach

- -

before

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

after

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

Printing the contents of an array

- -

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

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

Using thisArg

- -

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

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

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

- -
-

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

-
- -

An object copy function

- -

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

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

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

- -

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

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

Polyfill

- -

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

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

Đặc tả

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

Trình duyệt tương thích

- -
- - -

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

-
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/from/index.html b/files/vi/web/javascript/reference/global_objects/array/from/index.html deleted file mode 100644 index cee1cc84f7..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/from/index.html +++ /dev/null @@ -1,228 +0,0 @@ ---- -title: Array.from() -slug: Web/JavaScript/Reference/Global_Objects/Array/from -tags: - - Array - - ECMAScript 2015 - - JavaScript - - Phương Thức - - Tham khảo - - polyfill -translation_of: Web/JavaScript/Reference/Global_Objects/Array/from ---- -
{{JSRef}}
- -

Phương thức Array.from() tạo ra một thực thể Array mới được sao chép cạn (shallow-copied) từ các đối tượng giống mảng hoặc các đối tượng khả duyệt.

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

Cú pháp

- -
Array.from(arrayLike[, mapFn[, thisArg]])
-
- -

Tham số

- -
-
arrayLike
-
Đối tượng có tính chất giống mảng hoặc khả duyệt
-
mapFn{{Optional_inline}}
-
Hàm Map được gọi khi thực thi trên từng phần tử.
-
thisArg{{Optional_inline}}
-
Giá trị được sử dụng như this, thường là tham chiếu đến phạm vi của đối tượng gọi hàm mapFn.
-
- -

Giá trị trả về

- -

Một thực thể {{jsxref("Array")}} mới.

- -

Mô tả

- -

Array.from() cho phép tạo Array từ:

- - - -

Array.from() còn cung cấp thêm một tham số tuỳ chọn là mapFn, vốn là một hàm được tự động thực thi khi duyệt qua từng phần tử của {{jsxref("Array.prototype.map", "map")}}. Điểm khác biệt quan trọng của Array.from(obj, mapFn, thisArg) so với Array.from(obj).map(mapFn, thisArg) là nó không tạo ra mảng trung gian. Đây là điểm quan trọng cho các mảng kế thừa như typed arrays vì mảng trung gian nhất thiết sẽ có các giá trị được cắt ngắn để vừa với loại thích hợp.

- -

Thuộc tính length của phương thức from() là 1.

- -

Với ES2015 thì cú pháp class cho phép kế thừa từ cả các lớp có sẵn hoặc do người dùng định nghĩa, tất nhiên kể cả các phương thức tĩnh như Array.from cũng được kế thừa trong subclass, và kết quả trả về của from trong subclass là thực thể của subclass, không phải Array.

- -

Ví dụ

- -

Tạo mảng từ chuỗi

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

Tạo mảng từ tập hợp Set

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

Tạo mảng từ một Map

- -
var m = new Map([[1, 2], [2, 4], [4, 8]]);
-Array.from(m);
-// [[1, 2], [2, 4], [4, 8]]
-
-var mapper = new Map([['1', 'a'], ['2', 'b']]);
-Array.from(mapper.values());
-// ['a', 'b'];
-
-Array.from(mapper.keys());
-// ['1', '2'];
-
- -

Tạo mảng từ một đối tượng có tính chất giống mảng (arguments)

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

Hàm arrow trong Array.from

- -
// Using an arrow function as the map function to
-// manipulate the elements
-Array.from([1, 2, 3], x => x + x);
-// [2, 4, 6]
-
-
-// Generate a sequence of numbers
-// Since the array is initialized with `undefined` on each position,
-// the value of `v` below will be `undefined`
-Array.from({length: 5}, (v, i) => i);
-// [0, 1, 2, 3, 4]
-
- -

Polyfill

- -

Array.from đã được thêm vào tiêu chuẩn ECMA-262 trong ấn bản thứ 6 (ES2015); như vậy nó có thể không có mặt trong các bản hiện thực khác của ECMA-262 khác. Bạn có thể giải quyết vấn đề này bằng cách chèn đoạn mã sau vào đầu các đoạn mã JavaScript cho phép sử dụng Array.from trong các bản thực thi không hỗ trợ Array.from.

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

Đặc tả

- - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES2015', '#sec-array.from', 'Array.from')}}{{Spec2('ES2015')}}Khởi tạo.
{{SpecName('ESDraft', '#sec-array.from', 'Array.from')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- -
- - -

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

-
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/includes/index.html b/files/vi/web/javascript/reference/global_objects/array/includes/index.html deleted file mode 100644 index bc4b1980f4..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/includes/index.html +++ /dev/null @@ -1,135 +0,0 @@ ---- -title: Array.prototype.includes() -slug: Web/JavaScript/Reference/Global_Objects/Array/includes -tags: - - JavaScript - - Mảng - - Phương Thức - - Pollyfill - - Prototype - - Tham khảo -translation_of: Web/JavaScript/Reference/Global_Objects/Array/includes ---- -
{{JSRef}}
- -

Phương thức includes() kiểm tra xem phần tử đã cho có tồn tại trong mảng hay không, trả về kết quả true hoặc false.

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

Cú pháp

- -
arr.includes(valueToFind[, fromIndex])
-
- -

Các tham số

- -
-
valueToFind
-
-

Giá trị muốn kiểm tra.

- -
-

Lưu ý: Khi kiểm tra chuỗi hoặc kí tự, includes() sẽ phân biệt hoa thường.

-
-
-
fromIndex {{optional_inline}}
-
Vị trí trong mảng để bắt đầu tìm kiếm valueToFind; đầu tìm kiếm tại fromIndex khi fromIndex mang giá trị dương, hoặc tại array.length + fromIndex khi fromIndex  mang giá trị âm (sử dụng {{interwiki("wikipedia", "absolute value", "giá trị tuyệt đối")}} của fromIndex làm số lượng kí tự tính từ cuối mảng làm vị trí bắt đầu). Giá trị mặc định là 0.
-
- -

Giá trị trả về

- -

Có kiểu {{jsxref("Boolean")}}, trả về true nếu valueToFind được tìm thấy trong mảng (hoặc một phần của mảng được xác định bởi fromIndex nếu có). Các giá trị "không" được coi là bằng nhau (-0 sẽ bằng 0 và +0), nhưng false thì không bằng 0.

- -
-

Lưu ý: Về mặt kĩ thuật, includes() sử dụng thuật toán sameValueZero để kiểm tra phần tử đã cho có tìm thấy hay không.

-
- -

Ví dụ

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

fromIndex lớn hơn hoặc bằng độ dài mảng

- -

Nếu fromIndex lớn hơn hoặc bằng độ dài mảng, trả về kết quả false

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

Computed index nhỏ hơn 0

- -

Nếu fromIndex là số âm, computed index sẽ được dùng làm vị trí bắt đầu để tìm kiếm valueToFind. Nếu computed index nhỏ hơn hoặc bằng -1 * array.length, phần tử đã cho sẽ được tìm kiếm trong toàn bộ mảng (tương tự như fromIndex bằng 0).

- -
// độ dài mảng là 3
-// fromIndex là -100
-// computed index là 3 + (-100) = -97
-
-var arr = ['a', 'b', 'c'];
-
-arr.includes('a', -100); // true
-arr.includes('b', -100); // true
-arr.includes('c', -100); // true
-arr.includes('a', -2); // false
- -

includes() used as a generic method

- -

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

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

Đặc tả

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

Khả năng tương thích của trình duyệt

- -
- - -

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

-
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/index.html b/files/vi/web/javascript/reference/global_objects/array/index.html deleted file mode 100644 index 151242e596..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/index.html +++ /dev/null @@ -1,433 +0,0 @@ ---- -title: Array -slug: Web/JavaScript/Reference/Global_Objects/Array -tags: - - Array - - JavaScript -translation_of: Web/JavaScript/Reference/Global_Objects/Array ---- -
{{JSRef}}
- -

Đối tượng Array trong JavaScript là đối tượng toàn cục được dùng để xây dựng nên các mảng; là những đối tượng cấp cao và giống một dạng danh sách.

- -

Tạo một Mảng

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

Truy cập (bằng chỉ mục) đến một phần tử của Mảng

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

Lặp qua một Mảng

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

Thêm phần tử vào cuối Mảng

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

Xóa phần tử từ cuối Mảng

- -
var last = fruits.pop(); // xoá bỏ Orange (từ vị trí cuối)
-// ["Apple", "Banana"];
-
- -

Xóa phần tử từ đầu Mảng

- -
var first = fruits.shift(); // xoá bỏ Apple từ vị trí đầu
-// ["Banana"];
-
- -

Thêm phần tử vào đầu Mảng

- -
var newLength = fruits.unshift('Strawberry') // thêm vào vị trí đầu
-// ["Strawberry", "Banana"];
-
- -

Tìm chỉ mục của một phần tử trong Mảng

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

Xóa một phần tử bằng chỉ mục của nó

- -
var removedItem = fruits.splice(pos, 1); // đây là cách để xoá bỏ một phần tử
-
-// ["Strawberry", "Mango"]
- -

Xóa các phần tử bắt đầu từ vị trí của chỉ mục

- -
var vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot'];
-console.log(vegetables);
-// ["Cabbage", "Turnip", "Radish", "Carrot"]
-
-var pos = 1, n = 2;
-
-var removedItems = vegetables.splice(pos, n);
-// đây là cách để xoá các phần tử, n định nghĩa số phần tử cần xoá bỏ,
-// từ vị trí đó (pos) trở đi đến cuối mảng.
-
-console.log(vegetables);
-// ["Cabbage", "Carrot"] (mảng ban đầu đã bị thay đổi)
-
-console.log(removedItems);
-// ["Turnip", "Radish"]
- -

Sao chép một Mảng

- -
var shallowCopy = fruits.slice(); // đây là cách để tạo một bản sao
-// ["Strawberry"]
-
- -

Cú pháp

- -
[ element0 , element1 , ..., elementN ]
-new Array(element0 , element1 [, ... [, elementN ]])
-new Array(arrayLength)
- -
-
nguyên tố N
-
Một mảng JavaScript được khởi tạo với các yếu tố nhất định, ngoại trừ trong trường hợp một đối số duy nhất được truyền vào mảng xây dựng và lập luận đó là một con số. (Xem bên dưới). Lưu ý rằng trường hợp đặc biệt này chỉ áp dụng cho các mảng JavaScript tạo ra với các mảng xây dựng, không mảng literals tạo ra với cú pháp khung.
-
arrayLength
-
Nếu đối số duy nhất được truyền cho các mảng constructor là một số nguyên giữa 0 và 2 32 -1 (bao gồm), điều này trả về một mảng JavaScript mới với chiều dài thiết lập để con số đó. Nếu đối số là số nào khác, một {{jsxref ("Global_Objects / RangeError", "RangeError")}} ngoại lệ được ném ra.
-
- -

Miêu tả

- -

Mảng là đối tượng danh sách giống như nguyên mẫu mà có phương pháp để thực hiện traversal và đột biến hoạt động. Cả chiều dài của một mảng JavaScript hay các loại của các yếu tố của nó được cố định. Vì chiều dài kích thước của một mảng lớn hoặc thu nhỏ bất cứ lúc nào, các mảng JavaScript là không đảm bảo được dày đặc. Nói chung, đây là những đặc điểm thuận tiện; nhưng nếu các tính năng này không được mong muốn sử dụng cụ thể của bạn, bạn có thể xem xét sử dụng các mảng gõ.

- -

Một số người nghĩ rằng bạn không nên sử dụng một mảng như là một mảng kết hợp . Trong mọi trường hợp, bạn có thể sử dụng đồng bằng {{jsxref ("Global_Objects / Object", "đối tượng")}} thay vào đó, mặc dù làm như vậy đi kèm với hãy cẩn thận của mình. Xem các bài viết từ điển JavaScript nhẹ với các phím tùy ý như là một ví dụ.

- -

Truy cập vào các phần tử mảng

- -

Mảng JavaScript được zero-lập chỉ mục: phần tử đầu tiên của mảng là lúc chỉ số 0 , và các yếu tố cuối cùng là chỉ số tương đương với giá trị của của mảng {{jsxref ("Array.length", "chiều dài")}} tài sản trừ đi 1.

- -
var arr = ['đây là yếu tố đầu tiên "," đây là yếu tố thứ hai'];
-console.log(arr[0]); // Nhật ký này là yếu tố đầu tiên '
-console.log(arr[1]); // Nhật ký này là yếu tố thứ hai '
-console.log(arr[arr.length - 1]); // Nhật ký này là yếu tố thứ hai '
-
- -

Các phần tử mảng là thuộc tính đối tượng trong cùng một cách mà toString là một thuộc tính, nhưng cố gắng để truy cập vào một phần tử của mảng như sau ném một lỗi cú pháp, bởi vì tên sở hữu là không hợp lệ:

- -
console.log(arr.0); // Một lỗi cú pháp
-
- -

Có gì đặc biệt về mảng JavaScript và các thuộc tính gây ra điều này là. Tính JavaScript bắt đầu bằng một chữ số không thể được tham chiếu với ký hiệu dấu chấm; và phải được truy cập bằng cách sử dụng ký hiệu khung. Ví dụ, nếu bạn đã có một đối tượng với một thuộc tính có tên '3D' , nó chỉ có thể được tham chiếu bằng cách sử dụng ký hiệu khung. Ví dụ như:

- -
var years = [1950, 1960, 1970, 1980, 1990, 2000, 2010];
-console.log(years.0); // Một lỗi cú pháp
-console.log(years[0]); // Đúng cú pháp
-
- -
renderer.3d.setTexture (model, 'character.png'); // Một lỗi cú pháp
-renderer['3D']setTexture (model, 'character.png.'); // Đúng cú pháp
-
- -

Lưu ý rằng trong ví dụ 3d , '3D' đã được trích dẫn. Có thể trích dẫn các chỉ số mảng JavaScript cũng như (ví dụ, năm ['2'] thay vì năm [2] ), mặc dù nó không cần thiết. 2 trong năm [2] là bị cưỡng chế vào một chuỗi các công cụ JavaScript thông qua một tiềm ẩn toString chuyển đổi. Chính vì lý do này mà '2''02' sẽ chỉ đến hai khe cắm khác nhau trên năm đối tượng và các ví dụ sau đây có thể là sự thật :

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

Tương tự, thuộc tính đối tượng đó xảy ra để được dành riêng chỉ có thể được truy cập như các chuỗi trong ký hiệu khung:

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

Mối quan hệ giữa chiều dài và số thuộc tính

- -

Một mảng của JavaScript {{jsxref ("Array.length", "chiều dài")}} tài sản và tính toán được kết nối. Một số phương pháp mảng xây dựng trong (ví dụ, {{jsxref ("Array.join", "tham gia")}}, {{jsxref ("Array.slice", "lát cắt")}}, {{jsxref (" Array.indexOf "," indexOf ")}}, vv) có tính đến các giá trị của một mảng {{jsxref (" Array.length "," chiều dài ")}} tài sản khi chúng được gọi. Các phương pháp khác (ví dụ, {{jsxref ("Array.push", "đẩy")}}, {{jsxref ("Array.splice", "mối nối")}}, vv) cũng cho kết quả trong bản cập nhật tới một mảng của { {jsxref ("Array.length", "chiều dài")}} thuộc tính.

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

Khi thiết lập một thuộc tính trên một mảng JavaScript khi tài sản là một chỉ số mảng hợp lệ và chỉ số đó là ngoài giới hạn hiện tại của mảng, engine sẽ cập nhật thuộc tính {{jsxref ("Array.length", "chiều dài")}} của mảng cho phù hợp:

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

Tăng {{jsxref ("Array.length", "chiều dài")}}.

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

Giảm thuộc tính {{jsxref ("Array.length", "chiều dài")}} , tuy nhiên, xóa các phần tử.

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

Điều này được giải thích thêm về {{jsxref ("Array.length")}} trang.

- -

Tạo một mảng bằng cách sử dụng kết quả của một trận đấu

- -

Kết quả của một trận đấu giữa một biểu hiện thường xuyên và một chuỗi có thể tạo ra một mảng JavaScript. Mảng này có các tính chất và các yếu tố trong đó cung cấp thông tin về trận đấu. Một mảng đó được trả về bởi {{jsxref ("RegExp.exec")}}, {{jsxref ("String.match")}} và {{jsxref ("string.Replace")}}. Để giúp giải thích các thuộc tính và các yếu tố, nhìn vào ví dụ sau đây và sau đó tham khảo bảng dưới đây:

- -
// Trận đấu một d theo sau bởi một hoặc nhiều b theo sau bởi một d
-// Ghi phù hợp của b và d sau
-// Bỏ qua trường hợp
-
-var Myre = / d (b +) (d) / i;
-var myArray = myRe.exec('cdbBdbsbz');
-
- -

Các tính chất và các yếu tố trở về từ trận đấu này như sau:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Bất động sản / tửMiêu tảThí dụ
đầu vàoMột thuộc tính chỉ đọc phản ánh các chuỗi ban đầu dựa vào đó các biểu thức chính quy được kết hợp.cdbBdbsbz
mục lụcMột thuộc tính chỉ đọc mà là chỉ số không dựa trên các trận đấu trong chuỗi.1
[0]Một yếu tố chỉ đọc mà xác định các ký tự tương ứng cuối cùng.dbBd
[1], ... [n]Chỉ đọc các yếu tố đó chỉ định các trận đấu substring parenthesized, nếu có trong các biểu hiện thường xuyên. Số lượng các chuỗi con trong ngoặc có thể là không giới hạn.[1]: bB
- [2]: d
- -

Thuộc tính

- -
-
{{Jsxref ("Array.length")}}
-
Thuộc tính chiều dài của Array trong constructor (hàm dựng) có giá trị là 1.
-
{{Jsxref ("Array.prototype")}}
-
Cho phép bổ sung các thuộc tính cho tất cả các đối tượng mảng.
-
- -

Phương thức

- -
-
{{Jsxref ("Array.from()")}} {{experimental_inline}}
-
Tạo ra một Mảng mới từ một đối tượng giống mảng hoặc iterable.
-
{{Jsxref ("Array.isArray()")}}
-
Trả về true nếu một biến là một mảng, ngược lại false nếu không phải là mảng.
-
{{Jsxref ("Array.of()")}} {{experimental_inline}}
-
Tạo ra một Array mới với một số lượng các đối số, bất kể số hoặc loại của các đối số.
-
- -

Array instances

- -

Tất cả instance Array kế thừa từ {{jsxref ("Array.prototype")}}. Các đối tượng nguyên mẫu của Array constructor có thể được sửa đổi để ảnh hưởng đến tất cả các instance Array.

- -

Thuộc tính

- -
{{Page ('/ en-US / docs / Web / JavaScript / Reference / Global_Objects / Array / mẫu', 'Properties')}}
- -

Phương thức

- -

Phương thức mutator

- -
{{Page ('en-US / docs / Web / JavaScript / Reference / Global_Objects / Array / mẫu', 'Mutator_methods')}}
- -

Phương thức accessor

- -
{{Page ('en-US / docs / Web / JavaScript / Reference / Global_Objects / Array / mẫu', 'Accessor_methods')}}
- -

Phương thức lặp đi lặp lại

- -
{{Page ('en-US / docs / Web / JavaScript / Reference / Global_Objects / Array / mẫu', 'Iteration_methods')}}
- -

Array phương thức chung

- -

Đôi khi bạn muốn áp dụng phương thức mảng các chuỗi hoặc các đối tượng mảng giống khác (chẳng hạn như chức năng {{jsxref ("Chức năng / lập luận", "lý luận", "", 1)}}). Bằng cách này, bạn đối xử với một chuỗi như là một mảng kí tự (hoặc nếu không điều trị một phi mảng như là một mảng). Ví dụ, để kiểm tra xem tất cả các nhân vật trong biến str là một lá thư, bạn có thể viết:

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

Ký hiệu này là khá lãng phí và JavaScript 1.6 giới thiệu một cách viết tắt chung:

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

{{Jsxref ("Global_Objects / String", "Generics", "#String_generic_methods", 1)}} cũng có sẵn trên {{jsxref ("Global_Objects / String", "String")}}.

- -

Đây không phải là một phần của tiêu chuẩn ECMAScript và chúng không được hỗ trợ bởi các trình duyệt không phải là Gecko. Như một thay thế tiêu chuẩn, bạn có thể chuyển đổi đối tượng của bạn thành một mảng bằng cách sử dụng ({{jsxref ("Array.from ()")}}, mặc dù phương pháp này có thể không được hỗ trợ trong các trình duyệt cũ:

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

Ví dụ

- -

Tạo một mảng

- -

Ví dụ sau tạo một mảng, msgArray , với chiều dài 0, sau đó gán giá trị cho [0] msgArraymsgArray [99] , thay đổi độ dài của mảng đến 100.

- -
var msgArray = [];
-msgArray [0] = "Hello";
-msgArray [99] = 'World';
-
-if (msgArray.length === 100) {
-  console.log('Chiều dài là 100');
-}
-
- -

Tạo một mảng hai chiều

- -

Sau đây tạo ra một bàn cờ như là một mảng hai chiều của chuỗi. Động thái đầu tiên được thực hiện bằng cách sao chép 'p' trong (6,4) đến (4,4). Các vị trí cũ (6,4) được làm trống.

- -
var board = [
-  ['R','N','B','Q','K','B','N','R'],
-  ['P','P','P','P','P','P','P','P'],
-  [' ',' ',' ',' ',' ',' ',' ',' '],
-  [' ',' ',' ',' ',' ',' ',' ',' '],
-  [' ',' ',' ',' ',' ',' ',' ',' '],
-  [' ',' ',' ',' ',' ',' ',' ',' '],
-  ['p','p','p','p','p','p','p','p'],
-  ['r','n','b','q','k','b','n','r'] ];
-
-console.log(board.join('\n') + '\n\n');
-
-// Di chuyển King's Pawn về phía trước 2
-board[4][4] = board[6][4];
-board[6][4] = ' ';
-console.log(board.join('\n'));
- -

Đây là kết quả:

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

Sử dụng một mảng để sắp xếp một tập các giá trị

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

Kết quả là:

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

(Cột đầu tiên là index (chỉ mục))

- -

Thông số kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - -
Đặc điểm kỹ thuậtTrạng tháiChú thích
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa ban đầu.
{{SpecName("ES5.1", "#sec-15.4", "Array")}}{{Spec2("ES5.1")}}Phương thức mới được thêm vào: {{jsxref("Array.isArray")}}, {{jsxref("Array.prototype.indexOf", "indexOf")}}, {{jsxref("Array.prototype.lastIndexOf", "lastIndexOf ")}}, {{jsxref("Array.prototype.every", "every")}}, {{jsxref("Array.prototype.some", "some")}}, {{jsxref("Array. prototype.forEach","forEach")}}, {{jsxref("Array.prototype.map","map")}}, {{jsxref("Array.prototype.filter", "filter")}}, {{jsxref("Array.prototype.reduce", "reduce")}}, {{jsxref("Array.prototype.reduceRight", "reduceRight")}}
{{SpecName("ES6", "#sec-array-objects", "Array")}}{{Spec2 ("ES6")}}Phương thức mới được thêm vào: {{jsxref ("Array.from")}}, {{jsxref ("Array.of")}}, {{jsxref ("Array.prototype.find", "find")}}, {{jsxref ("Array.prototype.findIndex", "findIndex")}}, {{jsxref ("Array.prototype.fill", "fill")}}, {{jsxref ("Array.prototype.copyWithin", "copyWithin")}}
- -

Khả năng tương thích trình duyệt

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

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/indexof/index.html b/files/vi/web/javascript/reference/global_objects/array/indexof/index.html deleted file mode 100644 index 1ac4ea6321..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/indexof/index.html +++ /dev/null @@ -1,228 +0,0 @@ ---- -title: Array.prototype.indexOf() -slug: Web/JavaScript/Reference/Global_Objects/Array/indexOf -translation_of: Web/JavaScript/Reference/Global_Objects/Array/indexOf ---- -
{{JSRef}}
- -

Phương thức indexOf() sẽ trả về giá trị index đầu tiên của mảng, nơi mà nó đc tìm thấy trong mảng, hoặc trả về -1 nếu không tồn tại trong mảng.

- -
-

Chú ý: sử dụng indexOf() cho String, xem ở đây {{jsxref("String.prototype.indexOf()")}}.

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

Cú pháp

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

Các tham số

- -
-
searchElement
-
Phần tử cần tìm trong mảng.
-
fromIndex {{optional_inline}}
-
Vị trí index nơi bắt đầu tìm kiếm. Nếu index lớn hơn hoặc bằng số phần tử trong mảng, -1 sẽ được trả về, việc tìm kiếm sẽ không xảy ra. Nếu giá trị fromIndex là một số âm, vị trí index được tính từ cuối mảng. Lưu ý: cho dù fromIndex là số âm, kết quả tìm kiếm vẫn tính từ đầu mảng trở về sau. Nếu index bằng 0, cả mảng sẽ được tìm kiếm. Mặc định: 0 (cả mảng sẽ được tìm kiếm)
-
- -

Giá trị trả về

- -

Index đầu tiên của phần tử tìm thấy trong mảng; -1 nếu không tìm thấy.

- -

Mô tả

- -

indexOf() sẽ so sánh giá trị searchElement với các phần tử của mảng sử dụng so sánh chặt (tương đương với việc so sánh toán tử ba-dấu-bằng ===)

- -

Ví dụ

- -

Sử dụng indexOf()

- -

Ví dụ sau sẽ dùng indexOf() để tìm vị trí của giá trị trong một mảng.

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

Tìm tất cả các lần xuất hiện của phần tử

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

Xác định phần tử đã tồn tại trong mảng hay chưa và cập nhật lại mảng

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

Polyfill

- -

indexOf() được thêm vào đặc tả ECMA-262, phiên bản 5; nên có thể nó không có sẵn trong tất cả trình duyệt. Bạn có thể work around bằng cách thêm vào đoạn code bên dưới vào đầu script. Polyfill này sẽ giúp bạn vẫn sử dụng được indexOf dù trình duyệt nào đó vẫn chưa hỗ trợ sẵn. Giải thuật của polyfill này tương đương với đặc tả của indexOf trong ECMA-262, 5th edition, với yêu cầu {{jsxref("Global_Objects/TypeError", "TypeError")}} và {{jsxref("Math.abs()")}} không bị thay đổi.
-  

- -
// This version tries to optimize by only checking for "in" when looking for undefined and
-// skipping the definitely fruitless NaN search. Other parts are merely cosmetic conciseness.
-// Whether it is actually faster remains to be seen.
-if (!Array.prototype.indexOf)
-  Array.prototype.indexOf = (function(Object, max, min) {
-    "use strict"
-    return function indexOf(member, fromIndex) {
-      if (this === null || this === undefined)
-        throw TypeError("Array.prototype.indexOf called on null or undefined")
-
-      var that = Object(this), Len = that.length >>> 0, i = min(fromIndex | 0, Len)
-      if (i < 0) i = max(0, Len + i)
-      else if (i >= Len) return -1
-
-      if (member === void 0) {        // undefined
-        for (; i !== Len; ++i) if (that[i] === void 0 && i in that) return i
-      } else if (member !== member) { // NaN
-        return -1 // Since NaN !== NaN, it will never be found. Fast-path it.
-      } else                          // all else
-        for (; i !== Len; ++i) if (that[i] === member) return i
-
-      return -1 // if the value was not found, then return -1
-    }
-  })(Object, Math.max, Math.min)
- -

Tuy nhiên, nếu bạn muốn hiểu rõ mọi chi tiết của đặc tả ECMA, và không mấy quan tâm đến performance hay cần phải ngắn gọn, thì bạn nên tham khảo đoạn polyfill bên dưới:

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

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES5.1', '#sec-15.4.4.14', 'Array.prototype.indexOf')}}{{Spec2('ES5.1')}}Định nghĩa lần đầu. Được hiện thực trong JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.indexof', 'Array.prototype.indexOf')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.indexof', 'Array.prototype.indexOf')}}{{Spec2('ESDraft')}}
- -

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

- -
- - -

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

-
- -

Lưu ý về tương thích

- - - -

Tương tự

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/isarray/index.html b/files/vi/web/javascript/reference/global_objects/array/isarray/index.html deleted file mode 100644 index 9f34413842..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/isarray/index.html +++ /dev/null @@ -1,130 +0,0 @@ ---- -title: Array.isArray() -slug: Web/JavaScript/Reference/Global_Objects/Array/isArray -tags: - - Array - - ECMAScript 5 - - JavaScript - - Phương Thức - - Tham khảo - - polyfill -translation_of: Web/JavaScript/Reference/Global_Objects/Array/isArray ---- -
{{JSRef}}
- -

Array.isArray() là một phương thức để xác định liệu giá trị truyền vào có phải là một mảng kiểu {{jsxref("Array")}}.

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

Cú pháp

- -
Array.isArray(value)
- -

Tham Số

- -
-
value
-
Giá trị được kiểm tra.
-
- -

Giá trị trả về

- -

true nếu giá trị là kiểu mảng {{jsxref("Array")}}; false nếu không phải mảng.

- -

Mô tả

- -

Nếu giá trị là {{jsxref("Array")}}, trả về true, nếu không thì trả về false.

- -

Xem bài viết “Determining with absolute accuracy whether or not a JavaScript object is an array” để có thêm chi tiết. Giả sử ta có một {{jsxref("TypedArray")}} instance, false sẽ luôn được trả về.

- -

Ví dụ

- -
// all following calls return true
-Array.isArray([]);
-Array.isArray([1]);
-Array.isArray(new Array());
-// Little known fact: Array.prototype itself is an array:
-Array.isArray(Array.prototype);
-
-// all following calls return false
-Array.isArray();
-Array.isArray({});
-Array.isArray(null);
-Array.isArray(undefined);
-Array.isArray(17);
-Array.isArray('Array');
-Array.isArray(true);
-Array.isArray(false);
-Array.isArray({ __proto__: Array.prototype });
-
- -

instanceof vs isArray

- -

Để kiểm tra kiểu Array, nên dùng Array.isArray hơn là instanceof bởi vì nó vẫn ra đúng khi giá trị kiểm tra được truyền qua iframes.

- -
var iframe = document.createElement('iframe');
-document.body.appendChild(iframe);
-xArray = window.frames[window.frames.length-1].Array;
-var arr = new xArray(1,2,3); // [1,2,3]
-
-// Correctly checking for Array
-Array.isArray(arr);  // true
-// Considered harmful, because doesn't work through iframes
-arr instanceof Array; // false
-
- -

Polyfill

- -

Chạy mã dưới đây đầu tiên trước các mã khác sẽ tạo Array.isArray() nếu nó không có sẵn.

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

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES5.1', '#sec-15.4.3.2', 'Array.isArray')}}{{Spec2('ES5.1')}}Định nghĩa lần đầu. Được hiện thực trong JavaScript 1.8.5.
{{SpecName('ES6', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.isarray', 'Array.isArray')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- -
- - -

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

-
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/join/index.html b/files/vi/web/javascript/reference/global_objects/array/join/index.html deleted file mode 100644 index 12e5286a98..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/join/index.html +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: Array.prototype.join() -slug: Web/JavaScript/Reference/Global_Objects/Array/join -tags: - - JavaScript - - Mảng - - Phương Thức - - Prototype - - Tham khảo -translation_of: Web/JavaScript/Reference/Global_Objects/Array/join ---- -
{{JSRef}}
- -

Phương thức join() tạo ra một chuỗi mới bằng cách nối tất cả các phần tử của mảng (hoặc một array-like object), ngăn cách chúng bởi dấu phẩy hoặc một chuỗi ký tự xác định. Nếu mảng chỉ có một phần tử, kết quả sẽ trả về chính phần tử đó.

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

Cú pháp

- -
arr.join([chuỗi_ngăn_cách])
- -

Các tham số

- -
-
chuỗi_ngăn_cách {{optional_inline}}
-
Là một chuỗi xác định dùng để ngăn cách các phần tử liền kề của mảng. Nếu bỏ qua, các phần tử sẽ được ngăn cách bởi dấu phẩy (","). Nếu là một chuỗi rỗng, các phần tử sẽ nối với nhau mà không có bất kì ký tự nào ngăn cách chúng.
-
- -

Giá trị trả về

- -

Trả về một chuỗi với giá trị là các phần tử đã được nối với nhau. Nếu arr.length bằng 0, sẽ trả về một chuỗi rỗng.

- -

Mô tả

- -

Chuyển giá trị của tất cả các phần tử mảng thành chuỗi và nối chúng lại thành một chuỗi.

- -
-

Nếu phần tử mảng là undefined hoặc null, sẽ trả về một chuỗi rỗng.

-
- -

Ví dụ

- -

Nối chuỗi với 4 cách khác nhau

- -

Tạo một mảng a với ba phần tử, sau đó nối chúng lại với 4 cách khác nhau: dùng chuỗi_ngăn_cách mặc định, với dấu phẩy và khoảng cách, với dấu cộng và một chuỗi rỗng.

- -
var a = ['Wind', 'Water', 'Fire'];
-a.join();      // 'Wind,Water,Fire'
-a.join(', ');  // 'Wind, Water, Fire'
-a.join(' + '); // 'Wind + Water + Fire'
-a.join('');    // 'WindWaterFire'
- -

Nối một array-like object

- -

Nối array-like object (arguments), bằng cách gọi {{jsxref("Function.prototype.call")}} Array.prototype.join.

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

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiChú thích
{{SpecName('ES1')}}{{Spec2('ES1')}}Được đưa vào lần đầu trong JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.4.4.5', 'Array.prototype.join')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.join', 'Array.prototype.join')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.join', 'Array.prototype.join')}}{{Spec2('ESDraft')}}
- -

Khả năng tương thích của trình duyệt

- - - -

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

- -

Xem thêm các mục tương tự

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/map/index.html b/files/vi/web/javascript/reference/global_objects/array/map/index.html deleted file mode 100644 index fe3b6c1c37..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/map/index.html +++ /dev/null @@ -1,316 +0,0 @@ ---- -title: Array.prototype.map() -slug: Web/JavaScript/Reference/Global_Objects/Array/map -translation_of: Web/JavaScript/Reference/Global_Objects/Array/map ---- -
{{JSRef}}
- -

Phương thức map() giúp tạo ra một mảng mới với các phần tử là kết quả từ việc thực thi một hàm lên từng phần tử của mảng được gọi.

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

Cú pháp

- -
var new_array = arr.map(function callback(currentValue[, index[, array]]) {
-    // Trả về element mới cho new_array
-}[, thisArg])
- -

Tham số

- -
-
callback
-
Hàm để tạo ra phần tử cho mảng mới, nhận vào ba tham số: -
-
 
-
currentValue
-
Giá trị của phần tử trong mảng đang được xử lý
-
index{{optional_inline}}
-
Index của phần tử trong mảng đang được xử lý
-
array{{optional_inline}}
-
Mảng đang được gọi với map
-
-
-
thisArg{{optional_inline}}
-
Giá trị gán cho từ khóa this bên trong callback.
-
- -

Giá trị trả về

- -

Một mảng mới với phần tử là kết quả của hàm callback.

- -

Mô tả

- -

map sẽ gọi hàm callback lên từng phần tử của mảng, theo thứ tự trong mảng, và tạo ra một mảng mới chứa các phần tử kết quả. callback chỉ được gọi cho những vị trí index của mảng được gán giá trị, bao gồm cả undefined. Nó không được gọi cho những vị trí index trống (là các index của mảng chưa bao giờ được khởi tạo, bao gồm index chưa được gán giá trị hoặc đã bị xóa bằng delete).

- -

callback được gọi với ba tham số: giá trị của phần tử, index của phần tử, và chính mảng đang được gọi.

- -

Nếu tham số thisArg được truyền cho map, nó sẽ được gán cho từ khóa this trong hàm callback. Nếu không, giá trị undefined sẽ được dùng cho this với strict mode. Tóm lại, giá trị của từ khóa this trong hàm callback được xác định tuân theo các quy tắc thông thường để xác định this trong một hàm.

- -

map không làm thay đổi mảng ban đầu mà nó được gọi (mặc dù mảng ban đầu vẫn có thể bị thay đổi trong hàm callback).

- -

Các phần tử được map() xử lý được xác định từ đầu trước khi callback được gọi lần đầu tiên. Những phần tử mới được thêm vào sau khi map đã bắt đầu chạy sẽ không được callback gọi đến. Trong lúc map đang chạy, nếu những phần tử hiện tại của mảng bị thay đổi, thì giá trị mới của chúng sẽ được truyền cho hàm callback ngay tại thời điểm callback chạy qua. Những phần tử bị xóa sau khi map đã bắt đầu và trước khi đến lượt nó cũng sẽ bị bỏ qua.

- -

Do thuật toán đã quy định trong đặc tả, nếu như mảng ban đầu đã có sẵn những lỗ trống (index rỗng) thì sau khi được gọi với map, mảng đầu ra cũng sẽ có những index rỗng như mảng ban đầu.

- -

Ví dụ

- -

Map (ánh xạ) một mảng các số thành một mảng các giá trị căn bậc hai

- -

Đoạn code sau sẽ map một mảng các số thành một mảng mới chứa giá trị là căn bậc hai của các số trong mảng ban đầu.

- -
var numbers = [1, 4, 9];
-var roots = numbers.map(Math.sqrt);
-// mảng roots: [1, 2, 3]
-// mảng numbers vẫn là: [1, 4, 9]
-
- -

Dùng map để format lại các object trong mảng

- -

Đoạn code sau sẽ xử lý một mảng các object và trả về một mảng mới chứa các object đã được format lại:

- -
var kvArray = [{key: 1, value: 10},
-               {key: 2, value: 20},
-               {key: 3, value: 30}];
-
-var reformattedArray = kvArray.map(obj =>{
-   var rObj = {};
-   rObj[obj.key] = obj.value;
-   return rObj;
-});
-// reformattedArray bây giờ là: [{1: 10}, {2: 20}, {3: 30}],
-
-// kvArray vẫn là:
-// [{key: 1, value: 10},
-//  {key: 2, value: 20},
-//  {key: 3, value: 30}]
-
- -

Map một mảng các số sử dụng hàm có tham số

- -

Đoạn code sau minh họa cách thức map hoạt động khi callback có sử dụng tham số. Tham số này sẽ có giá trị của từng phần tử của mảng ban đầu khi map duyệt qua mảng này.

- -
var numbers = [1, 4, 9];
-var doubles = numbers.map(function(num) {
-  return num * 2;
-});
-
-// doubles is now [2, 8, 18]
-// numbers is still [1, 4, 9]
-
- -

Sử dụng map một cách độc lập

- -

Ví dụ sau sẽ minh họa cách dùng map lên một {{jsxref("String")}} một cách độc lập để trả về một mảng các mã byte trong bảng ASCII đại diện cho từng ký tự của chuỗi.

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

Sử dụng map với kết quả của querySelectorAll

- -

Ví dụ sau minh họa cách duyệt qua một tập các object (không phải mảng) trả về từ querySelectorAll. Trong trường hợp này, chúng ta sẽ in ra giá trị của tất cả các option được chọn (của các thẻ select) lên console: 

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

Cách trên có thể được giải quyết đơn giản hơn bằng cách sử dụng {{jsxref("Array.from()")}}.

- -

Trường hợp đặc biệt

- -

(ý tưởng từ bài viết này)

- -

Chúng ta hay dùng map với hàm một tham số (tham số đó chính là phần tử được duyệt). Và có một số hàm đặc biệt cũng thường được gọi với một tham số, mặc dù chúng có thêm tham số phụ không bắt buộc. Những thói quen này có thể dẫn đến những kết quả ngoài dự đoán.

- -
// Lấy ví dụ:
-['1', '2', '3'].map(parseInt);
-// Bạn sẽ nghĩ rằng kết quả là [1, 2, 3]
-// Nhưng kết quả lại là [1, NaN, NaN]
-
-// parseInt thường được dùng với 1 tham số, nhưng nó có thể nhận đến 2 tham số.
-// Tham số thứ nhất là một biểu thức giá trị và tham số thứ hai là cơ số
-// Với hàm callback của Array.prototype.map, nó sẽ nhận vào 3 tham số:
-// phần tử, index, mảng ban đầu
-// Tham số thứ 3 sẽ được parseInt bỏ qua, nhưng tham số thứ 2 lại có vai trò
-// và sẽ dẫn đến kết quả không mong muốn.
-
-// Sau đây là kết quả thực thi tại từng phần tử:
-// parseInt(string, radix) -> map(parseInt(value, index))
-// lần chạy 1 (index là 0): parseInt('1', 0) // cho ta parseInt('1', 0) -> 1
-// lần chạy 2 (index là 1): parseInt('2', 1) // cho ta parseInt('2', 1) -> NaN
-// lần chạy 3 (index là 2): parseInt('3', 2) // cho ta parseInt('3', 2) -> NaN
-
-function returnInt(element) {
-  return parseInt(element, 10);
-}
-
-['1', '2', '3'].map(returnInt); // [1, 2, 3]
-// Thông qua hàm returnInt, kết quả trả về là mảng các số (như mong muốn)
-
-// Tương tự như trên, nhưng sử dụng một hàm arrow
-['1', '2', '3'].map( str => parseInt(str) );
-
-// Một cách nữa đơn giản hơn nhưng tránh được vấn đề hàm nhiều tham số:
-['1', '2', '3'].map(Number); // [1, 2, 3]
-// Tuy nhiên khác với `parseInt`, cách này sẽ giữ lại định dạng
-// số thập phân hoặc ký hiệu mũ từ chuỗi ban đầu
-['1.1', '2.2e2', '3e300'].map(Number); // [1.1, 220, 3e+300]
-
- -

Một ví dụ khác khi gọi map với parseInt là tham số cho callback:

- -
var xs = ['10', '10', '10'];
-
-xs = xs.map(parseInt);
-
-console.log(xs);
-// Kết quả trả về là 10,NaN,2 như đã lý giải ở trên.
- -

Polyfill

- -

map() chỉ được thêm vào đặc tả ECMA-262 với phiên bản lần thứ 5; cho nên nó có thể không tồn tại trong một số hiện thực (implementation) của đặc tả. Bạn có thể work around bằng cách thêm vào đoạn code bên dưới vào đầu script của bạn, cho phép sử dụng hàm map tại những nơi mà nó không được hỗ trợ sẵn. Giải thuật trong polyfill này tương đương với hàm map được mô tả trong đặc tả ECMA-262, 5th edition với điều kiện {{jsxref("Object")}}, {{jsxref("TypeError")}}, và {{jsxref("Array")}} không bị thay đổi và callback.call chính là hàm được định nghĩa trong {{jsxref("Function.prototype.call")}}.

- -
-

Ghi chú bản dịch: những đoạn comment trong code bên dưới trích từ đặc tả ECMA nên sẽ giữ nguyên.

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

Đặc Tả

- - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES5.1', '#sec-15.4.4.19', 'Array.prototype.map')}}{{Spec2('ES5.1')}}Định nghĩa lần đầu. Hiện thực trong JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.map', 'Array.prototype.map')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.map', 'Array.prototype.map')}}{{Spec2('ESDraft')}} 
- -

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

- -
- - -

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

-
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/of/index.html b/files/vi/web/javascript/reference/global_objects/array/of/index.html deleted file mode 100644 index fdd6d03d53..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/of/index.html +++ /dev/null @@ -1,92 +0,0 @@ ---- -title: Array.of() -slug: Web/JavaScript/Reference/Global_Objects/Array/of -translation_of: Web/JavaScript/Reference/Global_Objects/Array/of ---- -
{{JSRef}}
- -

Phương thức Array.of() được dùng để tạo ra một mảng mới với các phần tử được truyền vào thông qua tham số truyền vào.

- -

Cả Array.of()Array đều chấp nhận tham số đầu vào là các số nguyên để khởi tạo một mảng mới, tuy nhiên chúng ta cần lưu ý trong trường hợp chỉ truyền vào một giá trị nguyên,  Array.of() sẽ tạo ra một mảng số nguyên có một phần tử duy nhất, trong khi Array() ?sẽ tạo ra một mảng có số lượng phần tử rỗng (phần tử rỗng không mang giá trị undefined hoặc null)  tương ứng với giá trị số nguyên truyền vào.

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

 Cú pháp

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

Tham số

- -
-
elementN
-
Các phần tử dùng để khởi tạo mảng
-
- -

Giá trị trả về

- -

Kết quả sau khi thực thi sẽ trả về một mảng mới

- -

Mô tả

- -

Đây là một phương thức chuẩncủa ECMAScript 2015. Có thể tham khảo thêm Array.of and Array.from proposal và Array.of polyfill.

- -

Ví dụ

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

Polyfill

- -

Nếu trình duyệt không hỗ trợ Array.of(), có thể gắn đoạn mã JS sau và thực thi nó trước tất cả các đoạn mã JS khác.

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

Đặc tả

- - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES2015', '#sec-array.of', 'Array.of')}}{{Spec2('ES2015')}}Định nghĩa lần đầu.
{{SpecName('ESDraft', '#sec-array.of', 'Array.of')}}{{Spec2('ESDraft')}} 
- -

Tính tương thích giữa các trình duyệt

- -
- - -

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

-
- -

Tham khảo thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/pop/index.html b/files/vi/web/javascript/reference/global_objects/array/pop/index.html deleted file mode 100644 index b5740406a5..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/pop/index.html +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Array.prototype.pop() -slug: Web/JavaScript/Reference/Global_Objects/Array/pop -tags: - - JavaScript - - Mảng -translation_of: Web/JavaScript/Reference/Global_Objects/Array/pop ---- -
{{JSRef}}
- -

Phương thức pop() xoá phần tử cuối cùng của một mảng và trả về phần tử đó. Phương thức này làm thay đổi độ dài của mảng.

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

Cú pháp

- -
arr.pop()
- -

Giá trị trả về

- -

Phần tử bị xoá từ mảng; {{jsxref("undefined")}} nếu mảng rỗng.

- -

Mô tả

- -

The pop method removes the last element from an array and returns that value to the caller.
- Phương thức pop xoá phần tử cuối cùng của một mảng và trả về giá trị đó cho lời gọi.

- -

pop is intentionally generic; this method can be {{jsxref("Function.call", "called", "", 1)}} ?or {{jsxref("Function.apply", "applied", "", 1)}} to objects resembling arrays. Objects which do not contain a length property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner.

- -

Nếu bạn gọi pop() trên một mảng rỗng, nó trả về {{jsxref("undefined")}}.

- -

Ví dụ

- -

Xoá phần tử cuối cùng của một mảng

- -

Đoạn mã sau tạo mảng myFish chứa 4 phần tử, sau đó xoá phần tử cuối cùng.

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

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tả?Trạng tháiGhi chú
{{SpecName('ES3')}}{{Spec2('ES3')}}Định nghĩa lần đầu. Cài đặt trong JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.6', 'Array.prototype.pop')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.pop', 'Array.prototype.pop')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.pop', 'Array.prototype.pop')}}{{Spec2('ESDraft')}} 
- -

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

- -
- - -

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

-
- -

See also

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/push/index.html b/files/vi/web/javascript/reference/global_objects/array/push/index.html deleted file mode 100644 index 2b3e6cca4d..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/push/index.html +++ /dev/null @@ -1,136 +0,0 @@ ---- -title: Array.prototype.push() -slug: Web/JavaScript/Reference/Global_Objects/Array/push -translation_of: Web/JavaScript/Reference/Global_Objects/Array/push ---- -
{{JSRef}}
- -

Phương thức push() giúp thêm 1 hay nhiều  phần tử vào cuối mảng và trả về chiều dài mới của mảng.

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

Cú pháp

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

Tham số

- -
-
elementN
-
Các phần tử sẽ thêm vào cuối mảng.
-
- -

Giá trị trả về

- -

Giá trị mới của thuộc tính {{jsxref("Array.length", "length")}} của mảng mà phương thức được gọi thực thi.

- -

Mô tả

- -

Phương thức push giúp thêm các giá trị vào mảng.

- -

push là "intentionally generic". Phương thức này có thể được dùng với {{jsxref("Function.call", "call()")}} hoặc {{jsxref("Function.apply", "apply()")}} trên các đối tượng giống với mảng. Phương thức push phụ thuộc vào thuộc tính length để xác định vị trí bắt đầu thêm các giá trị mới. Nếu thuộc tính length không thể  convert thành số, vị trí bắt đầu sẽ là 0. Điều này cũng bao gồm cả trường hợp thuộc tính length không tồn tại, khi đó length sẽ được tạo.

- -

Các đối tượng tương tự mảng (array-like) như {{jsxref("Global_Objects/String", "strings", "", 1)}}, không thích hợp để áp dụng phương thức này, vì các chuỗi là bất biến.

- -

Ví dụ

- -

Thêm phần tử vào mảng

- -

Đoạn mã dưới đây tạo mảng sports gồm 2 phần tử, sau đó sẽ thêm 2 phần tử vào cuối mảng này. Biến total có giá trị là chiều dài mới của mảng.

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

Merge 2 mảng

- -

Ví dụ này sẽ sử dụng {{jsxref("Function.apply", "apply()")}} để thêm tất cả các phần tử từ mảng thứ 2 vào mảng đầu.

- -

Không sử dụng phương thức này nếu mảng thứ 2 (trong ví dụ này là moreVegs) quá lớn, vì số lượng tối đa các tham số mà 1  hàm có thể nhận là giới hạn. Xem thêm chi tiết {{jsxref("Function.apply", "apply()")}}.

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

Sử dụng một đối tượng theo kiểu tương tự mảng

- -

Như đã để cập ở trên, push là "intentionally generic", và chúng ta có thể lợi dụng điều đó. Array.prototype.push có thể được thực thi trên 1 đối tượng, như ví dụ dưới đây. Chú ý rằng chúng ta không tạo mảng để lưu trữ các đối tượng. Mà thay vào đó chúng ta lưu trữ trên chính bản thân đối tượng bằng cách sử dụng call trên Array.prototype.push để áp dụng phương thức như là đang thao tác với mảng, việc này có thể thực hiện được chính là nhờ cái cách mà JavaScript cho phép chúng ta thiết lập ngữ cảnh thực thi.

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

Chú ý rằng obj không phải là mảng, phương thức push vẫn tăng giá trị thuộc tính length của obj như khi chúng ta thao tác với 1 mảng thực sự.

- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES3')}}{{Spec2('ES3')}}Định nghĩa lần đầu. Hiện thực trong JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.7', 'Array.prototype.push')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.push', 'Array.prototype.push')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.push', 'Array.prototype.push')}}{{Spec2('ESDraft')}} 
- -

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

- -
- - -

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

-
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/reduce/index.html b/files/vi/web/javascript/reference/global_objects/array/reduce/index.html deleted file mode 100644 index c665d37ad3..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/reduce/index.html +++ /dev/null @@ -1,553 +0,0 @@ ---- -title: Array.prototype.reduce() -slug: Web/JavaScript/Reference/Global_Objects/Array/Reduce -translation_of: Web/JavaScript/Reference/Global_Objects/Array/Reduce ---- -
{{JSRef}}
- -

Phương thức reduce() dùng để thực thi một hàm lên từng phần tử của mảng (từ trái sang phải) với một biến tích lũy để thu về một giá trị duy nhất.

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

Cú pháp

- -
arr.reduce(callback[, initialValue])
- -

Các tham số

- -
-
callback
-
Hàm dùng để thực thi với từng phần tử (element) của mảng, nhận vào 04 tham số: -
-
accumulator
-
Biến tích lũy, truyền giá trị trả về của mỗi lần gọi callback; nó là giá trị tích lũy được trả về trong lần gọi callback trước, hoặc giá trị của tham số initialValue, nếu được cung cấp (xem bên dưới).
-
currentValue
-
Phần tử trong mảng hiện tại đang được xử lý.
-
currentIndex{{optional_inline}}
-
Chỉ mục (index) của phần tử đang được xử lý. Bắt đầu tại 0, nếu giá trị initialValue được cung cấp, và tại 1 nếu không có initialValue.
-
array{{optional_inline}}
-
Mảng đang được gọi với reduce().
-
-
-
initialValue{{optional_inline}}
-
Giá trị cho tham số thứ nhất (accumulator) của hàm callback trong lần gọi đầu tiên. Nếu giá trị ban đầu này không được cung cấp, phần tử đầu tiên của mảng sẽ được dùng. Do đó, gọi reduce() trên một mảng rỗng và không có giá trị ban đầu sẽ gây ra lỗi.
-
- -

Giá trị trả về

- -

Giá trị sau khi rút gọn.

- -

Mô tả

- -

reduce() thực thi hàm callback lên từng phần tử đang tồn tại trong mảng, bỏ qua những lỗ trống không giá trị, và nhận vào 04 tham số:

- - - -

Trong lần đầu tiên callback được gọi, accumulator and currentValue có thể có một trong hai giá trị. Nếu tham số initialValue được cung cấp cho reduce(), thì accumulator sẽ bằng initialValue, và currentValue sẽ bằng phần tử đầu tiên của mảng. Nếu không có initialValueaccumulator sẽ bằng phần tử đầu tiên của mảng, và currentValue sẽ bằng phần tử thứ hai.

- -
-

Ghi chú: Nếu initialValue không được cung cấp, reduce() sẽ thực thi callback bắt đầu từ index 1, bỏ qua index đầu tiên. Nếu initialValue được cung cấp, index sẽ bắt đầu từ 0.

-
- -

Nếu mảng rỗng, và initialValue không được cung cấp, gọi reduce() sẽ gây ra lỗi {{jsxref("TypeError")}}. Nếu mảng chỉ có một phần tử có giá trị (bất kể vị trí index) đồng thời không có initialValue, hoặc có initialValue nhưng mảng lại rỗng, thì giá trị duy nhất đó sẽ được trả về và callback sẽ không được gọi.

- -

Sẽ an toàn hơn nếu giá trị ban đầu được cung cấp, bởi vì có đến ba khả năng xảy ra nếu không có initialValue như ở ví dụ sau:

- -
var maxCallback = ( acc, cur ) => Math.max( acc.x, cur.x );
-var maxCallback2 = ( max, cur ) => Math.max( max, cur );
-
-// reduce() không có initialValue
-[ { x: 22 }, { x: 42 } ].reduce( maxCallback ); // 42
-[ { x: 22 }            ].reduce( maxCallback ); // { x: 22 }
-[                      ].reduce( maxCallback ); // TypeError
-
-// map/reduce; giải pháp hay hơn, và nó có thể áp dụng được cho mảng rỗng hoặc lớn hơn
-[ { x: 22 }, { x: 42 } ].map( el => el.x )
-                        .reduce( maxCallback2, -Infinity );
-
- -

Cách reduce() làm việc

- -

Giả sử có một đoạn code với reduce() được hiện thực như sau:

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

Callback sẽ được gọi bốn lần, với giá trị tham số và trả về trong mỗi lần gọi như sau:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
callbackaccumulatorcurrentValuecurrentIndexarraygiá trị trả về
lần gọi thứ nhất011[0, 1, 2, 3, 4]1
lần gọi thứ hai122[0, 1, 2, 3, 4]3
lần gọi thứ ba333[0, 1, 2, 3, 4]6
lần gọi thứ tư644[0, 1, 2, 3, 4]10
- -

Giá trị trả về cho reduce() chính là giá trị trả về của lần gọi callback cuối cùng (10).

- -

Bạn cũng có thể cung cấp một hàm mũi tên {{jsxref("Functions/Arrow_functions", "Arrow Function","",1)}} thay vì một hàm đầy đủ. Đoạn code sau đây sẽ cho kết quả giống như đoạn code ở trên:

- -
[0, 1, 2, 3, 4].reduce( (accumulator, currentValue, currentIndex, array) => accumulator + currentValue );
-
- -

Nếu bạn cung cấp giá trị initialValue cho tham số thứ hai của hàm reduce(), thì kết quả sẽ như bên dưới:

- -
[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => {
-    return accumulator + currentValue;
-}, 10);
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
callbackaccumulatorcurrentValuecurrentIndexarraygiá trị trả về
lần gọi thứ nhất1000[0, 1, 2, 3, 4]10
lần gọi thứ hai1011[0, 1, 2, 3, 4]11
lần gọi thứ ba1122[0, 1, 2, 3, 4]13
lần gọi thứ tư1333[0, 1, 2, 3, 4]16
lần gọi thứ năm1644[0, 1, 2, 3, 4]20
- -

Giá trị trả về cho reduce() lần này sẽ là 20.

- -

Ví dụ

- -

Tính tổng của tất cả các phần tử của mảng

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

Tương tự, nhưng viết bằng hàm arrow function

- -
var total = [ 0, 1, 2, 3 ].reduce(
-  ( accumulator, currentValue ) => accumulator + currentValue,
-  0
-);
- -

Tính tổng các giá trị bên trong một mảng các object

- -

Để tính tổng các giá trị nằm bên trong các phần tử là object, bạn phải cung cấp một giá trị ban đầu để từng phần tử đều được callback chạy qua (và accumulator luôn luôn là giá trị kiểu số):

- -
var initialValue = 0;
-var sum = [{x: 1}, {x:2}, {x:3}].reduce(function (accumulator, currentValue) {
-    return accumulator + currentValue.x;
-},initialValue)
-
-console.log(sum) // logs 6
-
- -

Tương tự, viết bằng arrow function:

- -
var initialValue = 0;
-var sum = [{x: 1}, {x:2}, {x:3}].reduce(
-    (accumulator, currentValue) => accumulator + currentValue.x
-    ,initialValue
-);
-
-console.log(sum) // logs 6
- -

Trải phẳng một mảng chứa nhiều mảng con

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

Tương tự, viết bằng arrow function:

- -
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
-  ( accumulator, currentValue ) => accumulator.concat(currentValue),
-  []
-);
-
- -

Đếm số lần xuất hiện của phần tử trong mảng

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

Nhóm các đối tượng theo giá trị property nào đó

- -
var people = [
-  { name: 'Alice', age: 21 },
-  { name: 'Max', age: 20 },
-  { name: 'Jane', age: 20 }
-];
-
-function groupBy(objectArray, property) {
-  return objectArray.reduce(function (acc, obj) {
-    var key = obj[property];
-    if (!acc[key]) {
-      acc[key] = [];
-    }
-    acc[key].push(obj);
-    return acc;
-  }, {});
-}
-
-var groupedPeople = groupBy(people, 'age');
-// groupedPeople is:
-// {
-//   20: [
-//     { name: 'Max', age: 20 },
-//     { name: 'Jane', age: 20 }
-//   ],
-//   21: [{ name: 'Alice', age: 21 }]
-// }
-
- -

Ghép các mảng con bên trong các object sử dụng toán tử spread và initialValue

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

Xóa các phần tử bị trùng trong mảng

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

Chạy các Promise theo trình tự

- -
/**
- * Runs promises from array of functions that can return promises
- * in chained manner
- *
- * @param {array} arr - promise arr
- * @return {Object} promise object
- */
-function runPromiseInSequence(arr, input) {
-  return arr.reduce(
-    (promiseChain, currentFunction) => promiseChain.then(currentFunction),
-    Promise.resolve(input)
-  );
-}
-
-// promise function 1
-function p1(a) {
-  return new Promise((resolve, reject) => {
-    resolve(a * 5);
-  });
-}
-
-// promise function 2
-function p2(a) {
-  return new Promise((resolve, reject) => {
-    resolve(a * 2);
-  });
-}
-
-// function 3  - will be wrapped in a resolved promise by .then()
-function f3(a) {
- return a * 3;
-}
-
-// promise function 4
-function p4(a) {
-  return new Promise((resolve, reject) => {
-    resolve(a * 4);
-  });
-}
-
-const promiseArr = [p1, p2, f3, p4];
-runPromiseInSequence(promiseArr, 10)
-  .then(console.log);   // 1200
-
- -

Tổ hợp các hàm và gọi chuyền (piping)

- -
// Building-blocks to use for composition
-const double = x => x + x;
-const triple = x => 3 * x;
-const quadruple = x => 4 * x;
-
-// Function composition enabling pipe functionality
-const pipe = (...functions) => input => functions.reduce(
-    (acc, fn) => fn(acc),
-    input
-);
-
-// Composed functions for multiplication of specific values
-const multiply6 = pipe(double, triple);
-const multiply9 = pipe(triple, triple);
-const multiply16 = pipe(quadruple, quadruple);
-const multiply24 = pipe(double, triple, quadruple);
-
-// Usage
-multiply6(6); // 36
-multiply9(9); // 81
-multiply16(16); // 256
-multiply24(10); // 240
-
-
- -

Hiện thực lại map() sử dụng reduce()

- -
if (!Array.prototype.mapUsingReduce) {
-  Array.prototype.mapUsingReduce = function(callback, thisArg) {
-    return this.reduce(function(mappedArray, currentValue, index, array) {
-      mappedArray[index] = callback.call(thisArg, currentValue, index, array);
-      return mappedArray;
-    }, []);
-  };
-}
-
-[1, 2, , 3].mapUsingReduce(
-  (currentValue, index, array) => currentValue + index + array.length
-); // [5, 7, , 10]
-
-
- -

Polyfill

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

Nếu bạn thực sự cần chức năng này trên những engine JavaScript không hỗ trợ Object.defineProperty(), bạn không nên thêm polyfill này vào Array.prototype bởi vì không có cách nào làm cho nó không-duyệt-qua (non-enumerable) được (property mới sẽ xuất hiện trong các vòng lặp for).

- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES5.1', '#sec-15.4.4.21', 'Array.prototype.reduce()')}}{{Spec2('ES5.1')}}Định nghĩa lần đầu. Hiện thực trong JavaScript 1.8.
{{SpecName('ES6', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.reduce', 'Array.prototype.reduce()')}}{{Spec2('ESDraft')}} 
- -

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

- -
- - -

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

-
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/reduceright/index.html b/files/vi/web/javascript/reference/global_objects/array/reduceright/index.html deleted file mode 100644 index 7334a47f25..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/reduceright/index.html +++ /dev/null @@ -1,347 +0,0 @@ ---- -title: Array.prototype.reduceRight() -slug: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight -tags: - - JavaScr - - Mảng - - Phương thức - - Thuộc tính -translation_of: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight ---- -
{{JSRef}}
- -

Phương thức reduceRight() đảo ngược các giá trị trong mảng (từ phải sang trái), xử lý và trả về một giá trị duy nhất.

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

Xem thêm {{jsxref("Array.prototype.reduce()")}} cho việc sắp xếp từ trái qua phải.

- -

Cú pháp

- -
arr.reduceRight(callback[, initialValue])
- -

Tham số truyền vào

- -
-
callback
-
Hàm gọi thực thi mỗi giá trị của mảng, truyền vào 4 tham số: -
-
previousValue
-
Giá trí trả về của hàm callback sau khi xử lý phần tử trước nó hoặc là initialValue, nếu như nó là phần tử đầu tiên (Xem bên dưới.)
-
currentValue
-
Giá trị hiện tại đang được duyệt.
-
index
-
Chỉ số vị trí của phần tử trong mảng.
-
array
-
Mảng phần tử ban đầu.
-
-
-
initialValue
-
Giá trị không bắt buộc. Đối tượng sử dụng cho phần tử đầu tiền của mảng, khi mà chưa có kết quả nào từ hàm callback trả về.
-
- -

Return value

- -

Giá trị trả về từ việc rút gọn.

- -

Mô tả

- -

reduceRight xử lý từng phần tử trong mảng, trừ các phần tử vô giá trị (rỗng), truyền vào 4 tham số: giá trị ban đâu (or hoặc giá trị trả về sau khi xử lý một phần tử trước đó), giá trị phần tử hiện tại, vị trí phần tử hiện tại, và giá trị mảng ban đầu.

- -

Việc xử lý phần tử hiện tại sẽ làm trong dấu (...) :

- -
array.reduceRight(function(previousValue, currentValue, index, array) {
-  // ... xử lý tại đây
-});
-
- -

Trong lần đầu xử lý, tham số previousValue và currentValue có thể là một trong hai.

- -
    -
  1. Nếu tham sô initialValue được truyền vào reduceRight, thì tham số previousValue sẽ bằng giá trị  tham số initialValue (nói cách khác nó chính là initialValue) and currentValue sẽ là giá trị cuối cùng của mảng.
  2. -
  3. Nếu tham số initialValue không được truyền vào, thì previousValue sẽ là giá trị cuối cùng của mảng và currentValue sẽ là giá trị cuối cùng thứ 2 của mảng ( giá trị thứ 2 tỉnh từ cuối mảng ).
  4. -
- -

Nếu mảng rỗng và không có tham số initialValue  nào được truyền vào thì {{jsxref("TypeError")}} xảy ra. Nếu mảng chỉ có một phần tử (bất kể vị trí) à không có tham số initialValue  nào được truyền vào, hoặc nếu initialValue được truyền vào nhưng mảng lại rỗng, giá trị duy nhất sẽ được trả lại mà không cần tới hàm callback.

- -

Một số ví dụ mô tả luồng hoạt động của reduceRight, bạn có thể xem :

- -
[0, 1, 2, 3, 4].reduceRight(function(previousValue, currentValue, index, array) {
-  return previousValue + currentValue;
-});
-
- -

Bảng mô tả cách xử lý phần tử trong mảng ở ví dụ trên như sau:

- -

(*Tên gọi các tham số giữ nguyên để tiện theo dõi)

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
callbackpreviousValuecurrentValueindexarrayreturn value
lần 1433[0, 1, 2, 3, 4]7
lần 2722[0, 1, 2, 3, 4]9
lần 3911[0, 1, 2, 3, 4]10
lần 41000[0, 1, 2, 3, 4]10
- -

Giá trị trả về của hàm reduceRight sẽ là giá trị của lần thực thi cuối cùng (10).

- -

Và nếu bạn có đưa vào một giá trị initialValue, thì kết quả nó sẽ như thế này :

- -
[0, 1, 2, 3, 4].reduceRight(function(previousValue, currentValue, index, array) {
-  return previousValue + currentValue;
-}, 10);
-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
callbackpreviousValuecurrentValueindexarrayreturn value
first call1044[0, 1, 2, 3, 4]14
second call1433[0, 1, 2, 3, 4]17
third call1722[0, 1, 2, 3, 4]19
fourth call1911[0, 1, 2, 3, 4]20
fifth call2000[0, 1, 2, 3, 4]20
- -

Và tất nhiên giá trị trả về của hàm reduceRight sẽ là 20.

- -

Ví dụ

- -

Tính tổng các giá trị trong một mảng

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

Ghép nhiều mảng thành một mảng

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

Sự khác nhau giữa reduce và reduceRight

- -
var a = ['1', '2', '3', '4', '5'];
-var left  = a.reduce(function(prev, cur)      { return prev + cur; });
-var right = a.reduceRight(function(prev, cur) { return prev + cur; });
-
-console.log(left);  // "12345"
-console.log(right); // "54321"
- -

Polyfill 

- -

Đây là thuật ngữ dùng để chỉ các đoạn code được dùng để cung cấp một chức năng (hoặc công nghệ) của các trình duyệt hiện đại cho các trình duyệt cũ. Thông qua đó, các trang web sử dụng các công nghệ mới (như HTML5) có thể chạy ổn định trên các trình duyệt cũ chưa hỗ trợ.

- -

reduceRight đã được thêm vào chuẩn ECMA-262 trong lần sửa đổi thứ 5; do đó có thể nó không xuất hiện trong các trình duyệt chưa hỗ trợ nó . Bạn có thể dùng reduceRight bằng việc thêm đoạn mã sau vào code của bạn với khi làm việc với các trình duyệt không hỗ trợ nó.

- -
// Production steps of ECMA-262, Edition 5, 15.4.4.22
-// Reference: http://es5.github.io/#x15.4.4.22
-if ('function' !== typeof Array.prototype.reduceRight) {
-  Array.prototype.reduceRight = function(callback /*, initialValue*/) {
-    'use strict';
-    if (null === this || 'undefined' === typeof this) {
-      throw new TypeError('Array.prototype.reduce called on null or undefined');
-    }
-    if ('function' !== typeof callback) {
-      throw new TypeError(callback + ' is not a function');
-    }
-    var t = Object(this), len = t.length >>> 0, k = len - 1, value;
-    if (arguments.length >= 2) {
-      value = arguments[1];
-    } else {
-      while (k >= 0 && !(k in t)) {
-        k--;
-      }
-      if (k < 0) {
-        throw new TypeError('Reduce of empty array with no initial value');
-      }
-      value = t[k--];
-    }
-    for (; k >= 0; k--) {
-      if (k in t) {
-        value = callback(value, t[k], k, t);
-      }
-    }
-    return value;
-  };
-}
-
- -

Điều khoản

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.4.4.22', 'Array.prototype.reduceRight')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.
{{SpecName('ES6', '#sec-array.prototype.reduceright', 'Array.prototype.reduceRight')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.reduceright', 'Array.prototype.reduceRight')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9")}}{{CompatIE("9")}}{{CompatOpera("10.5")}}{{CompatSafari("4.0")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

 

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/reverse/index.html b/files/vi/web/javascript/reference/global_objects/array/reverse/index.html deleted file mode 100644 index 19e4c5ce6d..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/reverse/index.html +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: Array.prototype.reverse() -slug: Web/JavaScript/Reference/Global_Objects/Array/reverse -tags: - - Array - - JavaScript - - Mảng - - hàm -translation_of: Web/JavaScript/Reference/Global_Objects/Array/reverse ---- -
{{JSRef}}
- -

Hàm reverse() khi gọi bởi một mảng thì đảo ngược thứ tự của chính mảng đó. Phần tử đầu tiên của mảng trở thành phần tử cuối và ngược lại, phần tử cuối trở thành phần tử đầu tiên của mảng.

- -

Cú pháp

- -
arr.reverse()
- -

Tham số

- -

Không.

- -

Mô tả

- -

Hàm reverse đảo ngược thứ tự các phần tử của bản thân mảng, thay đổi mảng, và trả về tham chiếu của mảng đó.

- -

Ví dụ

- -

Đảo ngược thứ tự của một mảng

- -

Ví dụ dưới đây tạo một mảng myArray chứa 3 phần tử, sau đó đảo ngược thứ tự của các phần tử trong mảng.

- -
var myArray = ['one', 'two', 'three'];
-myArray.reverse();
-
-console.log(myArray) // ['three', 'two', 'one']
-
- -

Các đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa ban đầu. Được cài đặt ở JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.4.4.8', 'Array.prototype.reverse')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.reverse', 'Array.prototype.reverse')}}{{Spec2('ES6')}} 
- -

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

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/shift/index.html b/files/vi/web/javascript/reference/global_objects/array/shift/index.html deleted file mode 100644 index 19dd4b4aab..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/shift/index.html +++ /dev/null @@ -1,141 +0,0 @@ ---- -title: Array.prototype.shift() -slug: Web/JavaScript/Reference/Global_Objects/Array/shift -tags: - - Array - - JavaScript - - Method - - Mảng - - Nguyên mẫu - - Prototype - - hàm -translation_of: Web/JavaScript/Reference/Global_Objects/Array/shift ---- -
{{JSRef}}
- -

Hàm shift() sẽ xóa phần tử đầu tiên của một mảng và trả về phần tử đó. Hàm này sau khi thực thi sẽ làm thay đổi kích thước của mảng bị tác động.

- -

Cú pháp

- -
arr.shift()
- -

Giá trị trả về

- -

Phần tử đầu tiên của mảng.

- -

Mô tả

- -

Hàm shift sẽ xóa phần tử ở vị trí 0 trong mảng và dịch vị trí của các phần tử tiếp theo xuống, sau đó trả về giá trị của phần tử bị xóa. Nếu giá trị của thuộc tính {{jsxref("Array.length", "length")}} bằng 0, giá trị {{jsxref("undefined")}} được trả về.

- -

shift is intentionally generic; this method can be {{jsxref("Function.call", "called", "", 1)}} or {{jsxref("Function.apply", "applied", "", 1)}} to objects resembling arrays. Objects which do not contain a length property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner.

- -

Ví dụ

- -

Xóa bỏ một phần tử khỏi một mảng

- -

Đoạn mã code dưới đây hiển thị mảng myFish trước và sau khi xóa bỏ phần tử đầu tiên của mảng đó. Nó cũng hiển thị phần tử bị xóa bỏ:

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

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiChú thích
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Đã cài đặt từ phiên bản JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.9', 'Array.prototype.shift')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.shift', 'Array.prototype.shift')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.shift', 'Array.prototype.shift')}}{{Spec2('ESDraft')}}
- -

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

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
Tính năngChromeFirefox (Gecko)Internet ExplorerOperaSafari
Đã hỗ trợ{{CompatChrome("1.0")}}{{CompatGeckoDesktop("1.7")}}{{CompatIE("5.5")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
Tính năngAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Đã hỗ trợ{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Xem thêm các mục tương tự

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

Phương thức slice() trả về một bản sao tham chiếu (shallow copy) một phần của một mảng dưới dạng một mảng mới nhận các giá trị có chỉ số từ begin dến end (không bao gồm end). Mảng ban đầu không bị thay đổi.

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

Cú pháp

- -
arr.slice()
-arr.slice(begin)
-arr.slice(begin, end)
-
- -

Tham số

- -
-
begin {{optional_inline}}
-
Chỉ số bắt đầu chọn phần tử từ phần tử 0.
-
Nếu chỉ số này là số âm, được xem như tính ngược từ cuối của mảng. slice(-2) chọn hai phần tử cuối cùng của mảng.
-
Nếu begin là không xác định (undefined), slice bắt đầu từ chỉ số 0.
-
- -

     Nếu begin lớn hơn độ dài của mảng, một mảng trống được trả về.

- -
-
end {{optional_inline}}
-
Chỉ số ngừng chọn phần tử. slice chọn ra các phần tử có chỉ số trước chỉ số end.
-
Ví dụ, slice(1,4) chọn phần thử thứ hai, thứ ba và thứ tư (ở các chỉ số 1, 2, và 3).
-
Chỉ số âm tính ngược từ cuối mảng về. slice(2,-1) chọn các phần tử thứ ba cho đến phần tử sát cuối của mảng, không bao gồm phần từ cuối cùng ở chỉ số -1.
-
Nếu tham số end không được truyền vào, slice chọn đến cuối mảng (arr.length).
-
Nếu end lớn hơn độ dài mảng, slice chỉ chọn đến cuối mảng (arr.length).
-
- -

Gia trị trả về

- -

Một mảng mới chứa các phần tử được chọn.

- -

Mô tả

- -

slice không chỉnh sửa mảng ban đầu mà trả về bản sao tham chiếu (shallow copy, chỉ copy một cấp) phần được chọn từ mảng ban đầu. Các phần tử của mảng gốc được copy vào mảng trả về như sau:

- - - -

Nếu một phần tử được thêm vào một trong hai mảng, mảng còn lại không bị thay đổi.

- -

Ví dụ

- -

Trả về mảng con của một mảng 

- -
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
-var citrus = fruits.slice(1, 3);
-
-// fruits có giá trị ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
-// citrus có giá trị ['Orange','Lemon']
-
- -

Sử dụng slice

- -

Trong ví dụ sau, slice tạo một mảng mới, newCar, từ myCar. Cả hai chứa tham chiếu tới đối tượng myHonda. Khi trường color của đối tượng myHonda đổi sang purple, cả hai mảng đều thấy sự thay đổi này.

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

Đoạn mã trên in ra:

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

Các đối tượng giống kiểu mảng

- -

slice còn được dùng để thao tác với chuyển các đối tượng giống kiểu mảng (Array-like objects / collections) sang một mảng mới. Bạn chỉ cần gọi phương thức này trên đối tượng đó. Biến {{jsxref("Functions/arguments", "arguments")}} trong một hàm là ví dụ của một đối tượng kiểu mảng.

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

Để sử dụng phương thức này, sử dụng phương thức.call  {{jsxref("Function.prototype")}} để gọi [].slice.call(arguments) thay vì Array.prototype.slice.call. Hoặc đơn giản hơn là {{jsxref("Function.prototype.bind", "bind")}}.

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

Sử dụng trên nhiều trình duyệt

- -

Mặc dù các đối tượng trên trình duyệt (ví dụ các đối tượng DOM) không được yêu cầu theo chuẩn phải theo định nghĩa cả Mozilla khi chuyển  Array.prototype.slice và IE < 9 không làm thế, các phiên bản IE từ bản 9 hỗ trợ phương thức này. “Shimming” giúp đảm bảo phương thức này được hỗ trợ trên các trình duyệt khác nhau. Vì các trình duyệt ngày nay tiếp tục hỗ trợ tính năng này (IE, Mozilla, Chrome, Safari, and Opera), những nhà phát triển phần mềm đọc (DOM-supporting) mã slice dựa trên shim sẽ không bị nhầm lẫn về ngữ nghĩa; họ có thể tin tưởng dựa trên ngữ nghĩa này để mang lại hành vi được xem là tiêu chuẩn này. (Mã shim sửa IE cho tham số thứ hai của slice() để chuyển ra giá trị {{jsxref("null")}}/{{jsxref("undefined")}} không có trong các phiên bản trước của IE nhưng các trình duyệt ngày nay đều hỗ trợ, kể cả IE >= 9.)

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

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiBình luận
{{SpecName('ES3')}}{{Spec2('ES3')}}Định nghĩa ban đầu. Xuất hiện ở Javascript 1.2.
{{SpecName('ES5.1', '#sec-15.4.4.10', 'Array.prototype.slice')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.slice', 'Array.prototype.slice')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.slice', 'Array.prototype.slice')}}{{Spec2('ESDraft')}}
- -

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

- -
- - -

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

-
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/some/index.html b/files/vi/web/javascript/reference/global_objects/array/some/index.html deleted file mode 100644 index bbc279dc5c..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/some/index.html +++ /dev/null @@ -1,206 +0,0 @@ ---- -title: Array.prototype.some() -slug: Web/JavaScript/Reference/Global_Objects/Array/some -tags: - - ECMAScript 5 - - JavaScript - - Mảng - - Phương Thức - - Prototype - - Tham khảo -translation_of: Web/JavaScript/Reference/Global_Objects/Array/some ---- -
{{JSRef}}
- -

Phương thức some() kiểm tra xem có ít nhất một phần tử của mảng thoả điều kiện ở hàm được truyền vào hay không. Kết quả trả về có kiểu Boolean

- -
-

Chú ý: Phương thức này sẽ trả về false nếu mảng rỗng.

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

Cú pháp

- -
arr.some(callback(element[, index[, array]])[, thisArg])
- -

Các tham số

- -
-
callback
-
Hàm dùng để kiểm tra từng phần tử, nhận vào ba đối số: -
-
element
-
Phần tử đang được kiểm tra.
-
index {{Optional_inline}}
-
Chỉ mục của phần tử đang được kiểm tra.
-
array{{Optional_inline}}
-
Là bản thân mảng đã gọi phương thức some() ở trên.
-
-
-
thisArg{{Optional_inline}}
-
Được sử dụng làm giá trị this khi thực thi hàm callback.
-
- -

Giá trị trả về

- -

true khi hàm callback trả về một giá trị {{Glossary("truthy")}} nếu có ít nhất một phần tử của mảng thoả điều kiện. Ngược lại sẽ trả về false.

- -

Mô tả

- -

Phương thức some() thực thi hàm callback một lần và lặp qua từng phần tử của mảng cho đến khi hàm callback trả về một giá trị truthy (tức là true khi được chuyển sang kiểu Boolean). Nếu như có một phần tử thoả mãn, some() sẽ lập tức trả về true. Ngược lại sẽ trả về false. callback được gọi chỉ khi các phần tử của mảng có giá trị.

- -

callback được gọi với ba đối số: giá trị của phần tử, số chỉ mục của phần tử và mảng đang được lặp qua.

- -

Nếu như tham số thisArg được truyền vào some(), nó sẽ được sử dụng làm giá trị this của callback. Nếu bỏ qua, this sẽ có giá trị {{jsxref("undefined")}}. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function.

- -

some() không làm thay đổi mảng ban đầu.

- -

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

- -

Ví dụ

- -

Kiểm tra giá trị của các phần tử

- -

Ví dụ bên dưới đang kiểm tra xem có phần tử nào lớn hơn 10 hay không.

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

Kiểm tra giá trị của các phần tử sử dụng arrow function

- -

Arrow functions làm cho cú pháp trở nên gọn hơn.

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

Kiểm tra phần tử có tồn tại trong mảng hay không

- -

Hàm checkAvailability() bên dưới đang mô phỏng lại phương thức includes(), trả về true nếu phần tử có tồn tại trong mảng:

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

Kiểm tra phần tử có tồn tại trong mảng hay không sử dụng arrow function

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

Chuyển giá trị bất kì sang kiểu Boolean

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

Polyfill

- -

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

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

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiChú thích
{{SpecName('ES5.1', '#sec-15.4.4.17', 'Array.prototype.some')}}{{Spec2('ES5.1')}}Được đưa vào lần đầu trong JavaScript 1.6.
{{SpecName('ES6', '#sec-array.prototype.some', 'Array.prototype.some')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.some', 'Array.prototype.some')}}{{Spec2('ESDraft')}}
- -

Khả năng tương thích của trình duyệt

- -
- - -

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

-
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/sort/index.html b/files/vi/web/javascript/reference/global_objects/array/sort/index.html deleted file mode 100644 index 3b723bc8f9..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/sort/index.html +++ /dev/null @@ -1,248 +0,0 @@ ---- -title: Array.prototype.sort() -slug: Web/JavaScript/Reference/Global_Objects/Array/sort -translation_of: Web/JavaScript/Reference/Global_Objects/Array/sort -original_slug: Web/JavaScript/Reference/Global_Objects/Array/Sắp_xếp ---- -
{{JSRef}}
- -

Phương thức sort() sẽ sắp xếp các phần tử của mảng ngay tại chỗ (in place) và trả về mảng đó. Kết quả sắp xếp có thể không ổn định (stable). Cách sắp xếp mặc định là theo Unicode code point của chuỗi.

- -

Độ phức tạp về thời gian và không gian của thuật toán sắp xếp sẽ tùy vào cách hiện thực.

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

Cú Pháp

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

 

- -

Tham số

- -
-
compareFunction {{optional_inline}}
-
Hàm dùng để xác định thứ tự sắp xếp. Nếu bỏ qua, mảng sẽ được sắp xếp dựa vào giá trị Unicode code point của từng ký tự của chuỗi được chuyển đổi từ giá trị của phần tử.
-
- -

Giá trị trả về

- -

Mảng đã sắp xếp. Chú ý mảng này được sắp xếp in place, và không có bản sao được tạo.

- -

Mô Tả

- -

Nếu không truyền compareFunction vào, các phần tử sẽ được sẽ được quy đổi về chuỗi kí tự và được so sánh dựa trên thứ tự của chuỗi kí tự đó trong bảng mã Unicode. Chẳng hạn, "Banana" đứng trước "Cherry". Còn nếu so sánh số học, 9 đứng trước 80, nhưng bởi vì các chữ số đã được quy đổi về chuỗi kí tự, nên "80" sẽ đứng trước "9" theo bảng mã Unicode.

- -

Nếu truyền compareFunction vào, phần tử của mảng sẽ được sắp xếp dựa theo giá trị trả về của hàm so sánh. Nếu a và b là hai phần tử được so sánh, thì:

- - - -

Ví dụ đơn giản cho hàm so sánh:

- -
function compare(a, b) {
-  if (a nhỏ hơn b) {
-    return -1;
-  }
-  if (a lớn hơn b) {
-    return 1;
-  }
-  // a bằng b
-  return 0;
-}
-
- -

Để so sánh giữa các số, chỉ cần lấy a trừ cho b. Hàm dưới đây sẽ sắp xếp mảng theo chiều tăng dần (nếu mảng không chứa Infinity và NaN):

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

Phương thức sort có thể dùng dễ dàng với {{jsxref("Operators/function", "function expressions", "", 1)}} (và closure):

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

Các Object cũng có thể được sắp xếp với một trong những thuộc tính của chúng.

- -
var items = [
-  { name: 'Edward', value: 21 },
-  { name: 'Sharpe', value: 37 },
-  { name: 'And', value: 45 },
-  { name: 'The', value: -12 },
-  { name: 'Magnetic', value: 13 },
-  { name: 'Zeros', value: 37 }
-];
-
-// ?sắp xếp theo value (giá trị)
-items.sort(function (a, b) {
-  return a.value - b.value;
-});
-
-// sắp xếp theo name (tên)
-items.sort(function(a, b) {
-  var nameA = a.name.toUpperCase(); // bỏ qua hoa thường
-  var nameB = b.name.toUpperCase(); // bỏ qua hoa thường
-  if (nameA < nameB) {
-    return -1;
-  }
-  if (nameA > nameB) {
-    return 1;
-  }
-
-  // name trùng nhau
-  return 0;
-});
- -

Ví dụ

- -

 

- -

Tạo, hiển thị và sắp xếp một mảng

- -

Ví dụ sau sẽ tạo bốn mảng và hiển thị chúng ở dạng nguyên bản và dạng đã được sắp xếp. Những mảng số sẽ được sắp xếp bằng cách sử dụng và không sử dụng hàm so sánh.

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

Kết quả trả về như phía dưới. Như ta thấy, khi sử dụng hàm so sánh thì dù là ở dạng số hay dạng chuỗi kí tự, mảng luôn được sắp xếp đúng.

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

Sắp xếp kí tự ngoài mã ASCII

- -

Để sắp xếp kí tự ngoài ASCII, ví dụ chuỗi kí tự có dấu (e, é, è, a, ä, vân vân), chuỗi kí tự thuộc ngôn ngữ không phải tiếng Anh: hãy dùng {{jsxref("String.localeCompare")}}. Hàm này có thể so sánh các kí tự đó để chúng luôn trả về thứ tự đúng.

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

Sắp xếp cùng với map

- -

Hàm compareFunction có thể được gọi nhiều lần trên cùng một phần tử của mảng. Tuỳ thuộc vào bản chất của compareFunction, việc này có thể tốn nhiều chi phí ban đầu. Hàm compareFunction càng phức tạp và càng có nhiều phần tử phải sắp xếp, thì việc sắp xếp càng phải thông minh hơn, như là dùng thêm phương thức map chẳng hạn. Ý tưởng là truyền mảng vào một lần để sàng ra những phần tử cần sắp xếp và lưu chúng vào một mảng tạm, sắp xếp mảng tạm ấy rồi sàng lại mảng tạm sẽ ra được thứ tự mong muốn.

- -
// mảng cần sắp xếp
-var list = ['Delta', 'alpha', 'CHARLIE', 'bravo'];
-
-// temporary array holds objects with position and sort-value
-var mapped = list.map(function(el, i) {
-  return { index: i, value: el.toLowerCase() };
-})
-
-// sorting the mapped array containing the reduced values
-mapped.sort(function(a, b) {
-  if (a.value > b.value) {
-    return 1;
-  }
-  if (a.value < b.value) {
-    return -1;
-  }
-  return 0;
-});
-
-// container for the resulting order
-var result = mapped.map(function(el){
-  return list[el.index];
-});
-
- -

Đặc điểm kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTình trạngGhi chú
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa lần đầu.
{{SpecName('ES5.1', '#sec-15.4.4.11', 'Array.prototype.sort')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-array.prototype.sort', 'Array.prototype.sort')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-array.prototype.sort', 'Array.prototype.sort')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt tương thích

- -
- - -

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

-
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/splice/index.html b/files/vi/web/javascript/reference/global_objects/array/splice/index.html deleted file mode 100644 index a942e28e67..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/splice/index.html +++ /dev/null @@ -1,161 +0,0 @@ ---- -title: Array.prototype.splice() -slug: Web/JavaScript/Reference/Global_Objects/Array/splice -translation_of: Web/JavaScript/Reference/Global_Objects/Array/splice ---- -
{{JSRef}}
- -

Phương thức splice() thay đổi phần tử của mảng bằng cách xóa phần tử đang tồn tại và/hoặc thêm phần tử mới.

- -
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
-
-myFish.splice(2, 0, 'drum'); // chèn 'drum' vào vị trí 2
-// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]
-
-myFish.splice(2, 1); // xóa 1 phần tử từ vị trí 2
-// myFish is ["angel", "clown","mandarin", "sturgeon"]
- -

Cú pháp

- -
array.splice(start[deleteCount[item1[item2[...]]]])
- -

Các tham số 

- -
-
start
-
Vị trí để bắt đầu thay đổi mảng (mặc định là 0). Nếu lớn hơn độ dài của mảng, thì chỉ số start được thiết lập bằng độ dài của mảng. Nếu giá trị là âm , thì bắt đầu từ các phần từ cuối mảng (gốc là -1, -n ứng với vị thứ thứ n cuối cùng và viết là array.length - n) và sẽ set giá trị 0 nếu trị tuyệt đối lớn hơn độ dài mảng.
-
deleteCount {{optional_inline}}
-
Con số chỉ định số lượng các phần tử sẽ bị xóa.
-
Nếu deleteCount bị bỏ qua hoặc có giá trị lớn hơn hoặc bằng array.length - start (nếu giá trị lớn hơn số phần tử còn lại của mảng, bắt đầu từ  start), thì tất cả các phần tử từ vị trí start đến cuối mảng sẽ bị xóa bỏ.
-
Nếu deleteCount bằng 0 hoặc là số âm, không phần tử nào được xóa. Trong trường hợp này bạn sẽ phải xác định ít nhất 1 phần tử mới (xem bên dưới).
-
item1, item2, ... {{optional_inline}}
-
Các phần tử thêm vào mảng, bắt đầu từ chỉ số  start . Nếu không có, splice() thì sẽ chỉ xóa các phần tử trong mảng.
-
- -

Giá trị trả về

- -

Trả về một mảng chứa các phần từ bị xóa. Nếu chỉ có 1 phần từ bị xóa, trả về mảng chứa 1 phần tử. Nếu không có phần tử nào bị xóa, trả về mảng rỗng.

- -

Mô tả

- -

Nếu số các phần tử chèn vào khác với số các phần tử bị xóa đi. Mảng mới sẽ có độ dài khác.

- -

Ví dụ

- -

Xóa 0 phần tử từ vị trí số 2, và thêm "drum"

- -
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
-var removed = myFish.splice(2, 0, 'drum');
-
-// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]
-// removed is [], không có phần tử nào bị xóa
-
- -

Không xóa phần tử nào và thêm "drum" và "guitar" tại vị trí số 2

- - - -
 myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
-var removed = myFish.splice(2, 0, 'drum', 'guitar');
-
-// myFish is ["angel", "clown", "drum", "guitar", "mandarin", "sturgeon"]
-// removed is [], no elements removed
- - - -

Xóa 1 phần tử từ vị trí số 3

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

Xóa 1 phần tử mảng từ vị trí số 2 , và thêm phần tử "trumpet"

- -
var myFish = ['angel', 'clown', 'drum', 'sturgeon'];
-var removed = myFish.splice(2, 1, 'trumpet');
-
-// myFish is ["angel", "clown", "trumpet", "sturgeon"]
-// removed is ["drum"]
- -

Xóa 2 phần tử mảng từ vị trí số 0, và thêm "parrot", "anemone" và "blue"

- -
var myFish = ['angel', 'clown', 'trumpet', 'sturgeon'];
-var removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue');
-
-// myFish is ["parrot", "anemone", "blue", "trumpet", "sturgeon"]
-// removed is ["angel", "clown"]
- -

Xóa 2 phần tử mảng từ vị trí số 2 

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

Xóa 1 phần tử mảng từ vị trí số -2

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

Xóa mọi phần tử mảng phía sau vị trí số 2 (incl.)

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

Đặc điểm kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tả kỹ thuậtTình trạngChú ý
{{SpecName('ES3')}}{{Spec2('ES3')}}Định nghĩa sơ khai được ghi trong JavaScript 1.2
{{SpecName('ES5.1', '#sec-15.4.4.12', 'Array.prototype.splice')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.splice', 'Array.prototype.splice')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.splice', 'Array.prototype.splice')}}{{Spec2('ESDraft')}}
- -

Trình duyệt tương thích

- -
- - -

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

-
- -

Liên quan

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/tolocalestring/index.html b/files/vi/web/javascript/reference/global_objects/array/tolocalestring/index.html deleted file mode 100644 index 1c9072af63..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/tolocalestring/index.html +++ /dev/null @@ -1,167 +0,0 @@ ---- -title: Array.prototype.toLocaleString() -slug: Web/JavaScript/Reference/Global_Objects/Array/toLocaleString -translation_of: Web/JavaScript/Reference/Global_Objects/Array/toLocaleString ---- -
Hàm toLocaleString() trả về 1 chuỗi các phần tử trong mảng. Các phần tử này được chuyển đổi sang kiểu chuỗi nhờ hàm toLocalString và được ngăn cách với nhau bằng một xâu đặc biệt (ví dụ : dấu phẩy (,))
- -

Syntax

- -
arr.toLocaleString([locales[, options]]);
-
- -

Parameters

- -
-
locales {{optional_inline}}
-
A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the locales argument, see the {{jsxref("Intl")}} page.
-
options {{optional_inline}}
-
An object with configuration properties, for numbers see {{jsxref("Number.prototype.toLocaleString()")}}, and for dates see {{jsxref("Date.prototype.toLocaleString()")}}.
-
- -

Return value

- -

A string representing the elements of the array.

- -

Examples

- -

Using locales and options

- -

The elements of the array are converted to strings using their toLocaleString methods.

- - - -

Always display the currency for the strings and numbers in the prices array:

- -
var prices = ['¥7', 500, 8123, 12];
-prices.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' });
-
-// "¥7,¥500,¥8,123,¥12"
-
- -

For more examples, see also the {{jsxref("Intl")}}, {{jsxref("NumberFormat")}}, and {{jsxref("DateTimeFormat")}} pages.

- -

Polyfill

- -
// https://tc39.github.io/ecma402/#sup-array.prototype.tolocalestring
-if (!Array.prototype.toLocaleString) {
-  Object.defineProperty(Array.prototype, 'toLocaleString', {
-    value: function(locales, options) {
-      // 1. Let O be ? ToObject(this value).
-      if (this == null) {
-        throw new TypeError('"this" is null or not defined');
-      }
-
-      var a = Object(this);
-
-      // 2. Let len be ? ToLength(? Get(A, "length")).
-      var len = a.length >>> 0;
-
-      // 3. Let separator be the String value for the
-      //    list-separator String appropriate for the
-      //    host environment's current locale (this is
-      //    derived in an implementation-defined way).
-      // NOTE: In this case, we will use a comma
-      var separator = ',';
-
-      // 4. If len is zero, return the empty String.
-      if (len === 0) {
-        return '';
-      }
-
-      // 5. Let firstElement be ? Get(A, "0").
-      var firstElement = a[0];
-      // 6. If firstElement is undefined or null, then
-      //  a.Let R be the empty String.
-      // 7. Else,
-      //  a. Let R be ?
-      //     ToString(?
-      //       Invoke(
-      //        firstElement,
-      //        "toLocaleString",
-      //        « locales, options »
-      //       )
-      //     )
-      var r = firstElement == null ?
-        '' : firstElement.toLocaleString(locales, options);
-
-      // 8. Let k be 1.
-      var k = 1;
-
-      // 9. Repeat, while k < len
-      while (k < len) {
-        // a. Let S be a String value produced by
-        //   concatenating R and separator.
-        var s = r + separator;
-
-        // b. Let nextElement be ? Get(A, ToString(k)).
-        var nextElement = a[k];
-
-        // c. If nextElement is undefined or null, then
-        //   i. Let R be the empty String.
-        // d. Else,
-        //   i. Let R be ?
-        //     ToString(?
-        //       Invoke(
-        //        nextElement,
-        //        "toLocaleString",
-        //        « locales, options »
-        //       )
-        //     )
-        r = nextElement == null ?
-          '' : nextElement.toLocaleString(locales, options);
-
-        // e. Let R be a String value produced by
-        //   concatenating S and R.
-        r = s + r;
-
-        // f. Increase k by 1.
-        k++;
-      }
-
-      // 10. Return R.
-      return r;
-    }
-  });
-}
-
- -

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

- -

Specifications

- - - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-array.prototype.tolocalestring', 'Array.prototype.toLocaleString')}}
{{SpecName('ES Int Draft', '#sup-array.prototype.tolocalestring', 'Array.prototype.toLocaleString')}}
- -

Browser compatibility

- -
- - -

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

-
- -

See also

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/tostring/index.html b/files/vi/web/javascript/reference/global_objects/array/tostring/index.html deleted file mode 100644 index c62919e81e..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/tostring/index.html +++ /dev/null @@ -1,75 +0,0 @@ ---- -title: Array.prototype.toString() -slug: Web/JavaScript/Reference/Global_Objects/Array/toString -translation_of: Web/JavaScript/Reference/Global_Objects/Array/toString ---- -
{{JSRef}}
- -

Phương thức toString()trả về một chuỗi string đại diện cho mảng được chỉ định và các phần tử trong mảng đó.

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

Cú pháp

- -
arr.toString()
- -

Giá trị trả về

- -

Một chuỗi string đại diện cho mảng được chỉ định và các phần tử trong mảng đó.

- -

Mô tả

- -

Đối tượng {{jsxref("Array")}} ghi đè phương thức toString của {{jsxref("Object")}}. Đối với các array objects, phương thức toString nối mảng lại và trả về một chuỗi string chứa các phần tử trong mảng và được ngăn cách bởi dấu phẩy.

- -

Javascript tự động gọi phương thức toString khi một mảng được biểu diễn dưới dạng text hoặc khi một mảng được tham chiếu trong một string concate

- -

ECMAScript 5 semantics

- -

Bắt đầu từ JavaScript 1.8.5 (Firefox 4),  và phù hợp với ngữ nghĩa của ECMAScript 5th, phương thức toString() là phương thức chung và có thể sử dụng với bất cứ object nào. {{jsxref("Object.prototype.toString()")}} sẽ được gọi và  giá trị kết quả sẽ được trả về.

- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa ban đầu. Được triển khai trong JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.4.4.2', 'Array.prototype.toString')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-array.prototype.tostring', 'Array.prototype.toString')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-array.prototype.tostring', 'Array.prototype.toString')}}{{Spec2('ESDraft')}}
- -

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

- -
- - -

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

-
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/unshift/index.html b/files/vi/web/javascript/reference/global_objects/array/unshift/index.html deleted file mode 100644 index 580bd9bca3..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/unshift/index.html +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: Array.prototype.unshift() -slug: Web/JavaScript/Reference/Global_Objects/Array/unshift -translation_of: Web/JavaScript/Reference/Global_Objects/Array/unshift ---- -
{{JSRef}}
- -

Phương thức unshift() thêm một hoặc nhiều phần tử vào vị trí đầu mảng sau đó trả về chiều dài của mảng mới.

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

Syntax

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

Parameters

- -
-
elementN
-
Các phần tử được thêm vào đầu mảng.
-
- -

Return value

- -

Trả về độ dài mới của mảng {{jsxref("Array.length", "length")}}   sau khi thực hiện thêm phần tử.

- -

Description

- -

Phương thức unshift sẽ thêm vào đầu mảng các giá trị được truyền vào.

- -

unshift là "intentionally generic"; Phương thức này có thể được {{jsxref("Function.call", "gọi", "", 1)}} or {{jsxref("Function.apply", "áp dụng", "", 1)}} đối với các đối tượng giống như mảng. Objects which do not contain a length property reflecting the last in a series of consecutive, zero-based numerical properties may not behave in any meaningful manner.

- -

Chú ý rằng, Nếu truyền nhiều phần tử vào cùng lức như một biến, chúng sẽ được thêm vào vị trí đầu tiên của mảng, theo đúng vị trí ban đầu mà chúng được truyền vào. Việc gọi phương thức unshift với n phần tử trong một lần sẽ không trả về cùng kết quả (vị trí các phần tử) so với việc gọi n lần với mỗi lần 1 phần tử.

- -

Xem ví dụ bên dưới

- -
let arr = [4,5,6];
-
-arr.unshift(1,2,3);
-console.log(arr);
-// [1, 2, 3, 4, 5, 6]
-
-arr = [4,5,6]; // resetting the array
-
-arr.unshift(1);
-arr.unshift(2);
-arr.unshift(3);
-
-console.log(arr);
-// [3, 2, 1, 4, 5, 6]
-
- -

Examples

- -

Using unshift

- -
let arr = [1, 2];
-
-arr.unshift(0); // result of the call is 3, which is the new array length
-// arr is [0, 1, 2]
-
-arr.unshift(-2, -1); // the new array length is 5
-// arr is [-2, -1, 0, 1, 2]
-
-arr.unshift([-4, -3]); // the new array length is 6
-// arr is [[-4, -3], -2, -1, 0, 1, 2]
-
-arr.unshift([-7, -6], [-5]); // the new array length is 8
-// arr is [ [-7, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ]
-
- -

Specifications

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

Browser compatibility

- -
- - -

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

-
- -

See also

- - diff --git a/files/vi/web/javascript/reference/global_objects/array/values/index.html b/files/vi/web/javascript/reference/global_objects/array/values/index.html deleted file mode 100644 index 9460fdfbc3..0000000000 --- a/files/vi/web/javascript/reference/global_objects/array/values/index.html +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: Array.prototype.values() -slug: Web/JavaScript/Reference/Global_Objects/Array/values -translation_of: Web/JavaScript/Reference/Global_Objects/Array/values ---- -
{{JSRef}}
- -

Method values()trả về một Array Iterator object chứa các giá trị của mỗi index trong mảng.

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

Cú Pháp

- -
arr.values()
- -

Giá trị trả về

- -

Một object {{jsxref("Array")}} lặp lại mới.

- -

Ví dụ

- -

Sử dụng vòng lặp for...of loop

- -
var arr = ['a', 'b', 'c', 'd', 'e'];
-var iterator = arr.values();
-
-for (let letter of iterator) {
-  console.log(letter);
-}  //"a" "b" "c" "d" "e"
-
- -

Array.prototype.values là triển khai mặc định của Array.prototype[Symbol.iterator].

- -
Array.prototype.values === Array.prototype[Symbol.iterator]      //true
- -

Sử dụng vòng lặp .next()

- -
var arr = ['a', 'b', 'c', 'd', 'e'];
-var iterator = arr.values();
-iterator.next();               // Object { value: "a", done: false }
-iterator.next().value;         // "b"
-iterator.next()["value"];      // "c"
-iterator.next();               // Object { value: "d", done: false }
-iterator.next();               // Object { value: "e", done: false }
-iterator.next();               // Object { value: undefined, done: true }
-iteraror.next().value;         // undefined 
- -
-

Sử dụng một lần: đối tượng trình lặp mảng là một đối tượng sử dụng một lần hoặc tạm thời

-
- -

Ví dụ:

- -
var arr = ['a', 'b', 'c', 'd', 'e'];
- var iterator = arr.values();
- for (let letter of iterator) {
- console.log(letter);
-} //"a" "b" "c" "d" "e"
-for (let letter of iterator) {
-console.log(letter);
-} // undefined
-
- -

Lý do: khi next().done=true  hoặc  currentIndex>length thì vòng lặp for..of kết thúc. Xem tại Iteration protocols.

- -

Giá trị: không có giá trị nào được lưu trữ trong object lặp mảng; thay vào đó, nó lưu trữ địa chỉ của mảng được sử dụng trong quá trình tạo của nó và do đó phụ thuộc vào các giá trị được lưu trữ trong mảng đó.

- -
var arr = ['a', 'b', 'c', 'd', 'e'];
-var iterator = arr.values();
-console.log(iterator);        // Array Iterator {  }
-iterator.next().value;        // "a"
-arr[1]='n';
-iterator.next().value;        //  "n"
-
- -
-

nếu các giá trị trong mảng thay đổi thì các giá trị trong mảng lặp cũng thay đổi.

-
- - - -

Thông số kỹ thuật

- - - - - - - - - - - - -
Thông số kỹ thuật
{{SpecName('ESDraft', '#sec-array.prototype.values', 'Array.prototype.values')}}
- -

Tính tương thích của trình duyệt web

- -
- - -

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

-
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/arraybuffer/index.html b/files/vi/web/javascript/reference/global_objects/arraybuffer/index.html deleted file mode 100644 index 1cf512233b..0000000000 --- a/files/vi/web/javascript/reference/global_objects/arraybuffer/index.html +++ /dev/null @@ -1,141 +0,0 @@ ---- -title: ArrayBuffer -slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer -translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer ---- -
{{JSRef}}
- -
Đối tượng ArrayBuffer được sử dụng để biểu diễn một bộ đệm dữ liệu nhị phân nguyên gốc có độ dài cố định. Ta không thể trực tiếp thay đổi nội dung của một ArrayBuffer; mà thay vào đó là tạo ra một typed array objects hoặc một đối tượng {{jsxref("DataView")}} đại diện cho bộ đệm với một định dạng cụ thể, và sử dụng nó để đọc và ghi nội dung của bộ đệm.
- -
 
- -
{{EmbedInteractiveExample("pages/js/arraybuffer-constructor.html")}}
- - - -

Cú pháp

- -
new ArrayBuffer(length)
-
- -

Tham số

- -
-
length
-
Kích thước tính theo bytes của bộ đệm mảng cần tạo
-
- -

Giá trị trả về

- -

Là một ArrayBuffer mới có kích thước được chỉ định. Nội dung khởi tạo là 0.

- -

Ngoại lệ

- -

Lỗi {{jsxref("RangeError")}} sẽ được đưa ra nếu length lớn hơn  {{jsxref("Number.MAX_SAFE_INTEGER")}} (>= 2 ** 53) hoặc mang giá trị âm.

- -

Mô tả

- -

Hàm dựng ArrayBuffer tạo ra một  ArrayBuffer  dựa trên chiều dài đã cho tính theo byte

- -

Lấy một mảng đệm từ dữ liệu hiện có

- - - -

Thuộc tính

- -
-
ArrayBuffer.length
-
Thuộc tính chiều dài của hàm dựng của ArrayBuffer có giá trị là 1.
-
{{jsxref("ArrayBuffer.@@species", "get ArrayBuffer[@@species]")}}
-
Hàm dựng để tạo ra các đối tượng kế thừa
-
{{jsxref("ArrayBuffer.prototype")}}
-
Cho phép bổ sung các thuộc tính cho tất cả các đối tượng ArrayBuffer .
-
- -

Phương thức

- -
-
{{jsxref("ArrayBuffer.isView", "ArrayBuffer.isView(arg)")}}
-
Trả về true nếu tham số arg là một trong các views của ArrayBuffer, ví dụ như typed array objects hoặc {{jsxref("DataView")}}. Trả về false trong trường hợp ngược lại.
-
{{jsxref("ArrayBuffer.transfer", "ArrayBuffer.transfer(oldBuffer [, newByteLength])")}} {{experimental_inline}}
-
-
Trả về một ArrayBuffer nội dung lấy từ dữ liệu của oldBuffer và sau đó được cắt bớt hoặc không mở rộng thông qua newByteLength.
-
-
- -

Thực thể

- -

Tất cả các thực thể của  ArrayBuffer đều kế thừa từ {{jsxref("ArrayBuffer.prototype")}}.

- -

Thuộc tính

- -

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

- -

Phương thức

- -

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

- -
-
{{jsxref("ArrayBuffer.slice()")}} {{non-standard_inline}}
-
Cùng chức năng như {{jsxref("ArrayBuffer.prototype.slice()")}}.
-
- -

Ví dụ

- -

Ví dụu sau tạo ra một vùng đệm 8 byte với view của {{jsxref("Global_Objects/Int32Array", "Int32Array")}} ?trỏ đến bộ đệm

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

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('Typed Array')}}{{Spec2('Typed Array')}}?Thay thế bởi ECMAScript 6.
{{SpecName('ES6', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}{{Spec2('ES6')}}Initial definition in an ECMA standard. Specified that new is required.
{{SpecName('ESDraft', '#sec-arraybuffer-constructor', 'ArrayBuffer')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt tương thích

- - - -

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

- -

Ghi chú thêm về tính tương thích

- -

Với ECMAScript 2015, hàm dựng ArrayBuffer cần được khởi tạo với {{jsxref("Operators/new", "new")}}. Việc gọi một hàm dựng ArrayBuffer nhưng một hàm thông thường không có toán tử new sẽ gây ra lỗi {{jsxref("TypeError")}}.

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

Tham khảo thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/date/index.html b/files/vi/web/javascript/reference/global_objects/date/index.html deleted file mode 100644 index 7e485400e4..0000000000 --- a/files/vi/web/javascript/reference/global_objects/date/index.html +++ /dev/null @@ -1,260 +0,0 @@ ---- -title: Date -slug: Web/JavaScript/Reference/Global_Objects/Date -tags: - - Date - - JavaScript - - Vietnamese -translation_of: Web/JavaScript/Reference/Global_Objects/Date ---- -
{{JSRef}}
- -

Tạo ra một thể hiện JavaScript Date đại diện cho một khoảnh khắc trong thời gian. Đối tượng ngày được dựa trên giá trị thời gian là số mili giây kể từ ngày 1 tháng 1 năm 1970 UTC.

- -

Cú pháp

- -
new Date();
-new Date(value);
-new Date(dateString);
-new Date(year, month[, date[, hours[, minutes[, seconds[, milliseconds]]]]]);
-
- -
-

Lưu ý: Đối tượng JavaScript Date chỉ có thể được khởi tạo bằng cách gọi JavaScript Date như một constructor: gọi nó như là một hàm thông thường (tức là không có toán tử {{jsxref ("Operators / new", "new")}}) sẽ trả về một chuỗi thay vì một tượng Date; không giống như các kiểu đối tượng JavaScript khác, đối tượng JavaScript Date không có cú pháp rút gọn.

-
- -

Các tham số

- -
-

Chú ý: Trường hợp Date được gọi như một hàm khởi tạo với nhiều hơn một đối số, nếu các giá trị lớn hơn phạm vi hợp lý của chúng (ví dụ: 13 được cung cấp như là giá trị tháng hoặc 70 cho giá trị phút) thì giá trị liền kề sẽ được điều chỉnh. Ví dụ, new Date(2013, 13, 1) tương đương với new Date(2014, 1, 1), cả hai đều tạo ra một ngày cho 2014-02-01 (lưu ý rằng tháng này là 0). Tương tự cho các giá trị khác: new Date(2013, 2, 1, 0, 70) tương đương với new Date(2013, 2, 1, 1, 10) mà cả hai đều tạo ra một ngày cho 2013-03-01T01:10:00.

-
- -
-

Chú ý: Trường hợp Date được gọi như một hàm khởi tạo với nhiều hơn một đối số, các đối số xác định đại diện cho thời gian địa phương. Nếu UTC là mong muốn, sử dụng Date mới ({{jsxref ("Date.UTC ()", "Date.UTC (...)")}}) với cùng một đối số.

-
- -
-
value
-
Giá trị số nguyên đại diện cho số mili giây kể từ 01/01/1970-00:00:00 UTC.
-
dateString
-
Giá trị chuỗi đại diện cho một ngày. Chuỗi phải ở định dạng được công nhận bới phương thức {{jsxref("Date.parse()")}}. -
-

Lưu ý: Việc phân tách chuỗi ngày với constructor Date (và Date.parse, chúng là tương đương) đôi khi không như mong muốn do sự khác biệt và sự không nhất quán của trình duyệt. Hỗ trợ cho các chuỗi định dạng RFC 2822 chỉ là theo quy ước. Hỗ trợ các định dạng ISO 8601 khác với chuỗi "chỉ có ngày" (ví dụ: "1970-01-01") được coi như là UTC chứ không phải địa phương.

-
-
-
year
-
Giá trị số nguyên đại diện cho năm. Các giá trị từ 0 đến 99 ứng với các năm từ 1900 đến 1999.
-
month
-
Giá trị số nguyên đại diện cho tháng, bắt đầu với 0 cho Tháng Một đến 11 cho Tháng Mười Hai.
-
date
-
Tùy chọn. Giá trị số nguyên đại diện cho ngày trong tháng.
-
hours
-
Tùy chọn. Giá trị số nguyên đại diện cho giờ trong ngày.
-
minutes
-
Tùy chọn. Giá trị số nguyên đại diện cho phần phút của một thời gian.
-
seconds
-
Tùy chọn. Giá trị số nguyên đại diện cho phần giây của một thời gian.
-
milliseconds
-
Tùy chọn. Giá trị số nguyên đại diện cho phần mili giây của một thời gian.
-
- -

Mô tả

- - - -

Các thuộc tính

- -
-
{{jsxref("Date.prototype")}}
-
Cho phép thêm thuộc tính vào một đối tượng JavaScript Date.
-
Date.length
-
Giá trị của Date.length là 7. Đây là số lượng các đối số được xử lý bởi hàm khởi tạo.
-
- -

Các phương thức

- -
-
{{jsxref("Date.now()")}}
-
Trả về giá trị số tương ứng với thời gian hiện tại - số mili giây trôi qua kể từ ngày 1 tháng 1 năm 1970, 00:00:00, giờ UTC, với giây phút nhuận được bỏ qua.
-
{{jsxref("Date.parse()")}}
-
Phân tích cú pháp của một chuỗi đại diện ngày tháng và trả về số mili giây kể từ ngày 1 tháng 1 năm 1970, 00:00:00, giờ UTC, với giây phút nhuận được bỏ qua. -
-

Note: Việc phân tách cú pháp với Date.parse rất không chính xác do sự khác biệt giữa trình duyệt và sự không nhất quán..

-
-
-
{{jsxref("Date.UTC()")}}
-
Chấp nhận các tham số giống với dạng dài nhất của hàm khởi tạo (tức là 2 đến 7) và trả về số mili giây kể từ ngày 1 tháng 1 năm 1970, 00:00:00 giờ UTC, với giây phút nhuận được bỏ qua.
-
- -

Thể hiện của JavaScript Date

- -

Tất cả thể hiện của Date kế thừa từ {{jsxref("Date.prototype")}}. Đối tượng nguyên mẫu của hàm khởi tạo Date có thể được sửa đổi để ảnh hưởng đến tất cả thể hiện của Date.

- -

Date.prototype Methods

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

Các ví dụ

- -

Một số cách để tạo một đối tượng Date

- -

Các ví dụ sau đây cho thấy một số cách để tạo các ngày JavaScript:

- -
-

Chú ý: Việc phân tích các chuỗi ngày với constructor Date (và Date.parse, chúng là tương đương) rất không chính xác do sự khác biệt và sự không nhất quán của trình duyệt.

-
- -
var today = new Date();
-var birthday = new Date('October 30, 1996 15:27:08');
-var birthday = new Date('1996-10-30T15:27:08');
-var birthday = new Date(1996, 10, 30);
-var birthday = new Date(1996, 10, 30, 15, 27, 8);
-
- -

Các năm hai số ứng với 1900 - 1999

- -

Để tạo và lấy các ngày giữa các năm 0 đến 99 các phương thức {{jsxref("Date.prototype.setFullYear()")}} và {{jsxref("Date.prototype.getFullYear()")}} nên được sử dụng.

- -
var date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT).
-
-// Phương thức bị phản đối, 98 ứng với 1998 ở đây cũng vậy.
-date.setYear(98);           // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT).
-
-date.setFullYear(98);       // Sat Feb 01 0098 00:00:00 GMT+0000 (BST).
-
- -

Tính thời gian trôi qua

- -

Các ví dụ sau chỉ ra cách xác định thời gian trôi qua giữa hai ngày JavaScript trong mili giây.

- -

Do những ngày dài khác nhau (do thay đổi ánh sáng ban ngày), tháng và năm, thể hiện thời gian trôi qua theo đơn vị lớn hơn giờ, phút và giây đòi hỏi phải giải quyết một số vấn đề và cần được nghiên cứu kỹ trước khi cố gắng thử.

- -
// using Date objects
-var start = Date.now();
-
-// the event to time goes here:
-doSomethingForALongTime();
-var end = Date.now();
-var elapsed = end - start; // elapsed time in milliseconds
-
- -
// using built-in methods
-var start = new Date();
-
-// the event to time goes here:
-doSomethingForALongTime();
-var end = new Date();
-var elapsed = end.getTime() - start.getTime(); // elapsed time in milliseconds
-
- -
// to test a function and get back its return
-function printElapsedTime(fTest) {
-  var nStartTime = Date.now(),
-      vReturn = fTest(),
-      nEndTime = Date.now();
-
-  console.log('Elapsed time: ' + String(nEndTime - nStartTime) + ' milliseconds');
-  return vReturn;
-}
-
-yourFunctionReturn = printElapsedTime(yourFunction);
-
- -
-

Chú ý: Trong các trình duyệt hỗ trợ {{domxref("window.performance", "API Hiệu suất Web", "", 1)}} tính năng thời gian có độ phân giải cao, {{domxref("Performance.now()")}} có thể cung cấp các phép đo đáng tin cậy và chính xác về thời gian trôi qua hơn {{jsxref("Date.now()")}}.

-
- -

Thông số kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc điểm kỹ thuậtTrạng tháiChú thích
{{SpecName('ESDraft', '#sec-date-objects', 'Date')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-date-objects', 'Date')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-15.9', 'Date')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa ban đầu. Được thực hiện trong JavaScript 1.1.
- -

Khả năng tương thích trình duyệt

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
Đặc tínhChromeFirefox (Gecko)Internet ExplorerOperaSafari
Hỗ trợ cơ bản{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [2]{{CompatVersionUnknown}} [1]{{CompatVersionUnknown}} [1]
-
- -
- - - - - - - - - - - - - - - - - - - - - -
Đặc tínhAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Hỗ trợ cơ bản{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

[1] Một số trình duyệt có thể gặp sự cố khi phân tích ngày tháng: 3/14/2012 blog from danvk Comparing FF/IE/Chrome on Parsing Date Strings.

- -

[2] ISO8601 Date Format is not supported Trong Internet Explorer 8, và các phiên bản khác có thể có vấn đề chuyển đổi ngày tháng.

diff --git a/files/vi/web/javascript/reference/global_objects/date/parse/index.html b/files/vi/web/javascript/reference/global_objects/date/parse/index.html deleted file mode 100644 index 34b139a8f0..0000000000 --- a/files/vi/web/javascript/reference/global_objects/date/parse/index.html +++ /dev/null @@ -1,202 +0,0 @@ ---- -title: Date.parse() -slug: Web/JavaScript/Reference/Global_Objects/Date/parse -translation_of: Web/JavaScript/Reference/Global_Objects/Date/parse ---- -
{{JSRef}}
- -

Phương thức Date.parse() phân tích cú pháp của một chuỗi đại diện của một ngày và trả về số mili giây kể từ 01 tháng 01 năm 1970, 00:00:00 UTC hoặc NaN nếu chuỗi không nhận dạng được hoặc trong một số trường hợp, chứa các giá trị ngày không hợp lệ (ví dụ 2015-02-31).

- -

It is not recommended to use Date.parse as until ES5, parsing of strings was entirely implementation dependent. There are still many differences in how different hosts parse date strings, therefore date strings should be manually parsed (a library can help if many different formats are to be accommodated).

- -
{{EmbedInteractiveExample("pages/js/date-parse.html")}}
- - - -

Syntax

- -

Direct call:

- -
Date.parse(dateString)
-
- -

Implicit call:

- -
new Date(dateString)
-
- -

Parameters

- -
-
dateString
-
A string representing a simplification of the ISO 8601 calendar date extended format (other formats may be used, but results are implementation-dependent).
-
- -

Return value

- -

A number representing the milliseconds elapsed since January 1, 1970, 00:00:00 UTC and the date obtained by parsing the given string representation of a date. If the argument doesn't represent a valid date, {{jsxref("NaN")}} is returned.

- -

Description

- -

The parse() method takes a date string (such as "2011-10-10T14:48:00") and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This function is useful for setting date values based on string values, for example in conjunction with the {{jsxref("Date.prototype.setTime()", "setTime()")}} method and the {{jsxref("Global_Objects/Date", "Date")}} object.

- -

Date Time String Format

- -

The standard string representation of a date time string is a simplification of the ISO 8601 calendar date extended format (see Date Time String Format section in the ECMAScript specification for more details). For example, "2011-10-10" (date-only form), "2011-10-10T14:48:00" (date-time form), or "2011-10-10T14:48:00.000+09:00" (date-time form with milliseconds and time zone) can be passed and will be parsed. When the time zone offset is absent, date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time.

- -

While time zone specifiers are used during date string parsing to interpret the argument, the value returned is always the number of milliseconds between January 1, 1970 00:00:00 UTC and the point in time represented by the argument or NaN.

- -

Because parse() is a static method of {{jsxref("Date")}}, it is called as Date.parse() rather than as a method of a {{jsxref("Date")}} instance.

- -

Fall-back to implementation-specific date formats

- -
-

This section contains implementation-specific behavior that can be inconsistent across implementations.

-
- -

The ECMAScript specification states: If the String does not conform to the standard format the function may fall back to any implementation–specific heuristics or implementation–specific parsing algorithm. Unrecognizable strings or dates containing illegal element values in ISO formatted strings shall cause Date.parse() to return {{jsxref("NaN")}}.

- -

However, invalid values in date strings not recognized as simplified ISO format as defined by ECMA-262 may or may not result in {{jsxref("NaN")}}, depending on the browser and values provided, e.g.:

- -
// Non-ISO string with invalid date values
-new Date('23/25/2014');
-
- -

will be treated as a local date of 25 November, 2015 in Firefox 30 and an invalid date in Safari 7. However, if the string is recognized as an ISO format string and it contains invalid values, it will return {{jsxref("NaN")}} in all browsers compliant with ES5 and later:

- -
// ISO string with invalid values
-new Date('2014-25-23').toISOString();
-// returns "RangeError: invalid date" in all es5 compliant browsers
-
- -

SpiderMonkey's implementation-specific heuristic can be found in jsdate.cpp. The string "10 06 2014" is an example of a non–conforming ISO format and thus falls back to a custom routine. See also this rough outline on how the parsing works.

- -
new Date('10 06 2014');
-
- -

will be treated as a local date of 6 October, 2014 and not 10 June, 2014. Other examples:

- -
new Date('foo-bar 2014').toString();
-// returns: "Invalid Date"
-
-Date.parse('foo-bar 2014');
-// returns: NaN
-
- -

Differences in assumed time zone

- -
-

This section contains implementation-specific behavior that can be inconsistent across implementations.

-
- -

Given a non-standard date string of "March 7, 2014", parse() assumes a local time zone, but given a simplification of the ISO 8601 calendar date extended format such as "2014-03-07", it will assume a time zone of UTC (ES5 and ECMAScript 2015). Therefore {{jsxref("Date")}} objects produced using those strings may represent different moments in time depending on the version of ECMAScript supported unless the system is set with a local time zone of UTC. This means that two date strings that appear equivalent may result in two different values depending on the format of the string that is being converted.

- -

Examples

- -

Using Date.parse()

- -

The following calls all return 1546300800000.  The first according to ES5 will imply UTC time, and the others are specifying UTC timezone via the ISO date specification (Z and +00:00)

- -
Date.parse("2019-01-01")
-Date.parse("2019-01-01T00:00:00.000Z")
-Date.parse("2019-01-01T00:00:00.000+00:00")
-
- -

The following call, which does not specify a time zone will be set to 2019-01-01 at 00:00:00 in the local timezone of the system.

- -
Date.parse("2019-01-01T00:00:00")
-
- -

Non-standard date strings

- -
-

This section contains implementation-specific behavior that can be inconsistent across implementations.

-
- -

If IPOdate is an existing {{jsxref("Date")}} object, it can be set to August 9, 1995 (local time) as follows:

- -
IPOdate.setTime(Date.parse('Aug 9, 1995'));
-
- -

Some other examples of parsing non–standard date strings:

- -
Date.parse('Aug 9, 1995');
-
- -

Returns 807937200000 in time zone GMT-0300, and other values in other time zones, since the string does not specify a time zone and is not ISO format, therefore the time zone defaults to local.

- -
Date.parse('Wed, 09 Aug 1995 00:00:00 GMT');
-
- -

Returns 807926400000 no matter the local time zone as GMT (UTC) is provided.

- -
Date.parse('Wed, 09 Aug 1995 00:00:00');
-
- -

Returns 807937200000 in time zone GMT-0300, and other values in other time zones, since there is no time zone specifier in the argument and it is not ISO format, so is treated as local.

- -
Date.parse('Thu, 01 Jan 1970 00:00:00 GMT');
-
- -

Returns 0 no matter the local time zone as a time zone GMT (UTC) is provided.

- -
Date.parse('Thu, 01 Jan 1970 00:00:00');
-
- -

Returns 14400000 in time zone GMT-0400, and other values in other time zones, since no time zone is provided and the string is not in ISO format, therefore the local time zone is used.

- -
Date.parse('Thu, 01 Jan 1970 00:00:00 GMT-0400');
-
- -

Returns 14400000 no matter the local time zone as a time zone GMT (UTC) is provided.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.9.4.2', 'Date.parse')}}{{Spec2('ES5.1')}}Simplified ISO 8601 format added.
{{SpecName('ES6', '#sec-date.parse', 'Date.parse')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-date.parse', 'Date.parse')}}{{Spec2('ESDraft')}}
- -

Browser compatibility

- - - -

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

- -

Compatibility notes

- - - -

See also

- - diff --git a/files/vi/web/javascript/reference/global_objects/error/index.html b/files/vi/web/javascript/reference/global_objects/error/index.html deleted file mode 100644 index c1e957c6f0..0000000000 --- a/files/vi/web/javascript/reference/global_objects/error/index.html +++ /dev/null @@ -1,241 +0,0 @@ ---- -title: Lỗi -slug: Web/JavaScript/Reference/Global_Objects/Error -tags: - - JavaScript - - Lỗi - - Tham chiếu -translation_of: Web/JavaScript/Reference/Global_Objects/Error -original_slug: Web/JavaScript/Reference/Global_Objects/loi ---- -
{{JSRef}}
- -
Hàm Error tạo ra một đối tượng kiểu lỗi. Các thể hiện của đối tượng Error được ném ra khi xảy ra lỗi thực thi. Một đối tượng Error ngoài ra có thể được dùng như là một đối tượng căn bản cho các ngoại lệ do người dùng tự định nghĩa. Xem bên dưới các loại lỗi chuẩn được xây dựng sẵn.
- -

Cú pháp

- -
new Error([message[, fileName[, lineNumber]]])
- -

Tham số

- -
-
message
-
Tùy chọn. Một mô tả của lỗi rằng người dùng có thể đọc được.
-
fileName {{non-standard_inline}}
-
Tùy chọn. Giá trị của thuộc tính fileName trong quá trình tạo ra đối tượng Error. Các mặc định là tên của tập tin chứa đoạn mã gọi tới hàm Error().  
-
lineNumber {{non-standard_inline}}
-
Tuỳ chọn. Giá trị của thuộc tính lineNumber trong quá trình tạo ra đối tượng Error. Các mặc định là số dòng hiện tại đang gọi tới hàm Error().
-
- -

Mô tả

- -

Các lỗi thực thi dẫn đến các đối tượng Error được tạo ra và ném đi.

- -

Trang này ghi lại việc sử dụng đối tượng Error và cách sử dụng nó như là một hàm. Để biết danh sách các thuộc tính và phương thức được kế thừa bởi các thể hiện của Error, xem {{jsxref("Error.prototype")}}.

- -

Được sử dụng như là một hàm

- -

Khi Error được sử dụng như là một hàm -- không có từ khoá new, nó sẽ trả về một đối tượng Error. Do đó, gọi hàm Error cũng sẽ tạo ra cùng một đối tượng Error thông qua từ khóa new.

- -
// this:
-const x = Error('Tôi được tạo ra bằng cách sử dụng gọi hàm!');
-​​​​// tương tự như this
-const y = new Error('Tôi được xây dựng thông qua từ khoá "new"!');
- -

Các loại lỗi

- -

Bên cạnh hàm Error, còn có 7 hàm khác làm việc với lỗi trong JavaScript. Đối với ngoại lệ phía client, xem thêm tại Các câu lệnh xử lý ngoại lệ.

- -
-
{{jsxref("EvalError")}}
-
Tạo một thể hiện đại diện cho một lỗi xảy ra liên quan đến hàm toàn cục {{jsxref("Global_Objects/eval", "eval()")}}.
-
{{jsxref("InternalError")}} {{non-standard_inline}}
-
Tạo một thể hiện đại diện cho một lỗi xảy ra khi một lỗi bên trong bộ máy JavaScript được ném. Ví dụ: "quá nhiều đệ quy".
-
{{jsxref("RangeError")}}
-
Tạo một thể hiện đại diện cho một lỗi xảy ra khi một biến số hoặc tham số nằm ngoài phạm vi hợp lệ của nó.
-
{{jsxref("ReferenceError")}}
-
Tạo một thể hiện đại diện cho một lỗi xảy ra khi hủy tham chiếu của một tham chiếu không hợp lệ.
-
{{jsxref("SyntaxError")}}
-
Tạo một thể hiện đại diện cho một lỗi xảy ra trong khi phân tích cú pháp mã trong {{jsxref("Global_Objects/eval", "eval()")}}.
-
{{jsxref("TypeError")}}
-
Tạo một thể hiện đại diện cho một lỗi xảy ra khi một biến hoặc một tham số có kiểu không hợp lệ.
-
{{jsxref("URIError")}}
-
Tạo một thể hiện đại diện cho một lỗi xảy ra khi {{jsxref("Global_Objects/encodeURI", "encodeURI()")}} hoặc {{jsxref("Global_Objects/decodeURI", "decodeURI()")}} truyền các tham số không hợp lệ.
-
- -

Thuộc tính

- -
-
{{jsxref("Error.prototype")}}
-
Cho phép thêm các thuộc tính mới vào các thể hiện của Error.
-
- -

Phương thức

- -

Một đối tượng Error toàn cục không chứa phương thức riêng của nó, tuy nhiên, nó thừa hưởng các phương thức từ prototype.

- -

Các thể hiện của Error

- -
{{page('en-US/docs/JavaScript/Reference/Global_Objects/Error/prototype', 'Description')}}
- -

Các thuộc tính

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

Các phương thức

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

Các ví dụ

- -

Ném một lỗi thông thường

- -

Thông thường bạn tạo ra một đối tượng Error và muốn sử dụng nó cùng tới từ khoá {{jsxref("Statements/throw", "throw")}}. Bạn có thể bẫy lỗi bằng cách sử dụng cú pháp {{jsxref("Statements/try...catch", "try...catch")}}:

- -
try {
-  throw new Error('Whoops!');
-} catch (e) {
-  console.log(e.name + ': ' + e.message);
-}
-
- -

Xử lý một lỗi cụ thể

- -

Bạn có thể chọn cách chỉ xử lý các loại lỗi cụ thể bằng cách kiểm tra loại lỗi với thuộc tính {{jsxref("Object.prototype.constructor", "constructor")}} của lỗi hoặc, nếu bạn đang viết cho các công cụ JavaScript hiện đại, hãy dùng từ khoá {{jsxref("Operators/instanceof", "instanceof")}}:

- -
try {
-  foo.bar();
-} catch (e) {
-  if (e instanceof EvalError) {
-    console.log(e.name + ': ' + e.message);
-  } else if (e instanceof RangeError) {
-    console.log(e.name + ': ' + e.message);
-  }
-  // ... etc
-}
-
- -

Tùy biến các loại lỗi

- -

Bạn có thể muốn định nghĩa các loại lỗi của riêng mình được dẫn xuất từ Error để có thể throw new MyError() và sử dụng instanceof MyError để kiểm tra loại lỗi trong trình xử lý ngoại lệ. Điều này làm cho mã xử lý lỗi sạch hơn và nhất quán hơn. Xem "Cách tốt để thừa kế hàm Error trong JavaScript là gì?" trên StackOverflow để thảo luận chuyên sâu.

- -

Tuỳ biến lớp Error trong ES6

- -
-

Babel và các trình biên dịch khác sẽ không xử lý chính xác đoạn mã sau mà không cần cấu hình bổ sung.

-
- -
-

Một số trình duyệt đã thêm hàm CustomError trong ngăn xếp qua cách dùng class trong ES6.

-
- -
class CustomError extends Error {
-  constructor(foo = 'bar', ...params) {
-    // Pass remaining arguments (including vendor specific ones) to parent constructor
-    super(...params);
-
-    // Maintains proper stack trace for where our error was thrown (only available on V8)
-    if (Error.captureStackTrace) {
-      Error.captureStackTrace(this, CustomError);
-    }
-
-    // Custom debugging information
-    this.foo = foo;
-    this.date = new Date();
-  }
-}
-
-try {
-  throw new CustomError('baz', 'bazMessage');
-} catch(e){
-  console.log(e.foo); //baz
-  console.log(e.message); //bazMessage
-  console.log(e.stack); //stacktrace
-}
- -

Tuỳ biến đối tượng trong ES5

- -
-

Tất cả trình duyệt đã thêm hàm CustomError trong ngăn xếp qua cách khai báo chuẩn.

-
- -
function CustomError(foo, message, fileName, lineNumber) {
-  var instance = new Error(message, fileName, lineNumber);
-  instance.foo = foo;
-  Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
-  if (Error.captureStackTrace) {
-    Error.captureStackTrace(instance, CustomError);
-  }
-  return instance;
-}
-
-CustomError.prototype = Object.create(Error.prototype, {
-  constructor: {
-    value: Error,
-    enumerable: false,
-    writable: true,
-    configurable: true
-  }
-});
-
-if (Object.setPrototypeOf){
-  Object.setPrototypeOf(CustomError, Error);
-} else {
-  CustomError.__proto__ = Error;
-}
-
-
-try {
-  throw new CustomError('baz', 'bazMessage');
-} catch(e){
-  console.log(e.foo); //baz
-  console.log(e.message) ;//bazMessage
-}
- -

Các đặc điểm kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc điểm kỹ thuậtTrạng tháiChú thích
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa ban đầu. Được triển khai trong JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.11', 'Error')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-error-objects', 'Error')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-error-objects', 'Error')}}{{Spec2('ESDraft')}} 
- -

Tính tương thích của trình duyệt

- -
- - -

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

-
- -

Tham khảo

- - diff --git a/files/vi/web/javascript/reference/global_objects/function/call/index.html b/files/vi/web/javascript/reference/global_objects/function/call/index.html deleted file mode 100644 index 681b98474b..0000000000 --- a/files/vi/web/javascript/reference/global_objects/function/call/index.html +++ /dev/null @@ -1,148 +0,0 @@ ---- -title: Function.prototype.call() -slug: Web/JavaScript/Reference/Global_Objects/Function/call -tags: - - JavaScript - - Phương Thức - - hàm -translation_of: Web/JavaScript/Reference/Global_Objects/Function/call ---- -
{{JSRef}}
- -

Phương thức call() gọi một hàm với giá trị của this và các đối số riêng lẻ.

- -
-

Chú ý: Mặc dù hàm này có cú pháp gần giống với hàm {{jsxref("Function.prototype.apply", "apply()")}} nhưng có sự khác biệt cơ bản. Hàm call() nhận nhiều đối số riêng lẻ, còn hàm apply() nhận một mảng tập hợp của nhiều đối  số.

-
- -

Cú Pháp

- -
function.call(thisArg, arg1, arg2, ...)
- -

Tham số

- -
-
thisArg
-
Giá trị của this được đưa ra để gọi hàm. Lưu ý rằng this có thể không phải ?là giá trị thực tế được thấy bởi phương thức: Nếu phương thức là một hàm trong {{jsxref("Functions_and_function_scope/Strict_mode", "non-strict mode", "", 1)}} , giá trị {{jsxref("Global_Objects/null", "null")}} và {{jsxref("Global_Objects/undefined", "undefined")}} sẽ được thay thế với global object và các giá trị sơ khai (primitive) sẽ được chuyển thành các đối tượng (objects).
-
arg1, arg2, ...
-
Các đối số cho hàm.
-
- -

Giá trị trả về

- -

Kết quả của của việc gọi hàm với giá trị xác định của this và các đối số.

- -

Miêu tả

- -

Một đối tượng this có thể được chỉ định khi gọi một hàm có sẵn. this đề cập đến đối tượng hiện tại (current object), là đối tượng đang gọi (calling object). Với hàm call, bạn có thể viết một phương thức một lần duy nhất và sau đó thừa kế nó trong một đối tương khác mà không phải viết lại phương thức đó cho đối tượng mới.

- -

Ví du

- -

Sử dung call để chain constructors cho một đối tượng

- -

Bạn có thể sử dụng hàm call để chain constructors cho một đối tượng giống như trong Java. Trong ví dụ dưới đây, hàm khởi tại của đối tượng Product được định nghĩa với 2 tham số, name và price. Hai hàm Food và Toy gọi Product với tham số this , name và price. Product khởi tạo thuộc tính name và price, cả 2 hàm này định nghĩa category.

- -
function Product(name, price) {
-  this.name = name;
-  this.price = price;
-}
-
-function Food(name, price) {
-  Product.call(this, name, price);
-  this.category = 'food';
-}
-
-function Toy(name, price) {
-  Product.call(this, name, price);
-  this.category = 'toy';
-}
-
-var cheese = new Food('feta', 5);
-var fun = new Toy('robot', 40);
-
- -

 Sử dung hàm call để gọi một hàm ẩn danh (anonymous function)

- -

Trong ví dụ dưới đây, chúng ta tạo một hàm ẩn danh và sử dụng hàm call để gọi hàm đó nhận mọi đối tượng trong một mảng. Mục đích chính của hàm ẩn danh này là thêm tính năng hàm print cho mọi đối tượng, từ đó các đối tượng này có thể in ra vị trí của chúng trong mảng. Việc này có thể không cần thiết nhưng được đưa ra với mục đích ví dụ.

- -
var animals = [
-  { species: 'Lion', name: 'King' },
-  { species: 'Whale', name: 'Fail' }
-];
-
-for (var i = 0; i < animals.length; i++) {
-  (function(i) {
-    this.print = function() {
-      console.log('#' + i + ' ' + this.species
-                  + ': ' + this.name);
-    }
-    this.print();
-  }).call(animals[i], i);
-}
-
- -

 Sử dung hàm call để gọi hàm và đưa ra một giá trị cho đối tượng 'this'

- -

Trong ví dụ dưới đây khi chúng ta gọi hàm greet , giá trị của this trong hàm greet chính là đối tượng i.

- -
function greet() {
-  var reply = [this.person, 'Is An Awesome', this.role].join(' ');
-  console.log(reply);
-}
-
-var i = {
-  person: 'Douglas Crockford', role: 'Javascript Developer'
-};
-
-greet.call(i); // Douglas Crockford Is An Awesome Javascript Developer
-
- -

 Thông số kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.3.
{{SpecName('ES5.1', '#sec-15.3.4.4', 'Function.prototype.call')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-function.prototype.call', 'Function.prototype.call')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-function.prototype.call', 'Function.prototype.call')}}{{Spec2('ESDraft')}}
- -

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

- -
- - -

{{Compat("javascript.builtins.Function.call")}}

-
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/function/index.html b/files/vi/web/javascript/reference/global_objects/function/index.html deleted file mode 100644 index c94856a200..0000000000 --- a/files/vi/web/javascript/reference/global_objects/function/index.html +++ /dev/null @@ -1,150 +0,0 @@ ---- -title: Function -slug: Web/JavaScript/Reference/Global_Objects/Function -tags: - - Constructor - - Function - - JavaScript - - TopicStub - - hàm -translation_of: Web/JavaScript/Reference/Global_Objects/Function ---- -
{{JSRef}}
- -

Hàm Function tạo mới một đối tượng Function. Gọi hàm tạo trực tiếp có thể tạo các hàm một cách linh hoạt, nhưng gặp phải các vấn đề về bảo mật và hiệu suất tương tự như {{jsxref("eval")}}.

- -

Mỗi một JavaScript function thực sự là một đối tượng Function.

- -

Cú pháp

- -
new Function ([arg1[, arg2[, ...argN]],] functionBody)
- -

Tham số

- -
-
arg1, arg2, ... argN
-
Đây là các tên được sử dụng bởi hàm làm tên các tham số chính thức. Mỗi tên của tham số phải là một chuỗi tương ứng với một mã định danh JavaScript hợp lệ hoặc một danh sách các chuỗi tương tự được phân tách bằng dấu phẩy; ví dụ "x", "theValue" hoặc "a,b".
-
functionBody
-
Một chuỗi chứa các câu lệnh JavaScript bao gồm định nghĩa hàm.
-
- -

Mô tả

- -

Đối tượng Function được tạo ra thông qua hàm Function được chuyển đổi khi hàm được tạo ra. Điều này kém hiệu quả hơn so với việc khai báo một hàm với biểu thức hàm hoặc câu lệnh hàm và gọi nó trong mã của bạn, bởi vì các hàm đó được phân tích cú pháp với phần còn lại của mã. 

- -

Tất cả các tham số truyền cho hàm được coi là tên định danh của các tham số trong hàm, thứ mà sẽ được tạo, theo thứ tự chúng được truyền.

- -

Gọi Function như là một hàm (không sử dụng toán tử new) có tác dụng tương tự như gọi nó là một hàm thông thường.

- -

Các thuộc tính và phương thức của Function

- -

Một đối tượng Function toàn cục không có phương thức hoặc thuộc tính của riêng nó. Tuy nhiên, vì bản thân nó là một hàm, nó thừa hưởng một số phương thức và thuộc tính thông qua {{jsxref("Function.prototype")}}.

- -

Function prototype

- -

Các thuộc tính

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

Các phương thức

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

Các thể hiện của Function

- -

Các thể hiện của Function kế thừa các phương thức và thuộc tính từ {{jsxref("Function.prototype")}}. Cũng như tất cả các hàm khác, bạn có thể thay đổi prototype của hàm tạo để thực hiện thay đổi cho tất cả các thể hiện của Function.

- -

Các ví dụ

- -

Các tham số xác định cùng với hàm Function

- -

Đoạn mã sau tạo ra một đối tượng Function có hai tham số.

- -
// Ví dụ này có thể chạy trực tiếp trên JavaScript Console
-
-// Tạo một hàm gồm hai tham số và trả về tổng của những tham số đó
-var adder = new Function('a', 'b', 'return a + b');
-
-// Gọi hàm
-adder(2, 6);
-// > 8
-
- -

Những tham số "a" và "b"  là các tên tham số chính thức được sử dụng trong thân hàm, "return a + b".

- -

Sự khác biệt giữa hàm Function constructor và định nghĩa hàm

- -

Các hàm được tạo ra cùng với Function constructor không tạo ra sự khép kín với bối cảnh sáng tạo của chúng; chúng luôn luôn được tạo ra trong phạm vi toàn cục. Khi gọi, chúng sẽ chỉ có thể truy cập đên các biến cục bộ và biến toàn cục của chúng, chứ không phải các biến từ phạm vi mà Function constructor được tạo. Điều này khác với việc sử dụng {{jsxref("eval")}} với mã cho biểu thức hàm.

- -
var x = 10;
-
-function createFunction1() {
-    var x = 20;
-    return new Function('return x;'); // |x| trỏ tới |x| toàn cục
-}
-
-function createFunction2() {
-    var x = 20;
-    function f() {
-        return x; // |x| trỏ tới |x| cục bộ ngay bên trên
-    }
-    return f;
-}
-
-var f1 = createFunction1();
-console.log(f1());          // 10
-var f2 = createFunction2();
-console.log(f2());          // 20
-
- -

Các thông số kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Thông số kỹ thuậtTrạng tháiChú thích
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa ban đầu. Được triển khai trong JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.3', 'Function')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-function-objects', 'Function')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-function-objects', 'Function')}}{{Spec2('ESDraft')}} 
- -

Tính tương thích của trình duyệt

- -
- - -

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

-
- -

Tham khảo

- - diff --git a/files/vi/web/javascript/reference/global_objects/function/tosource/index.html b/files/vi/web/javascript/reference/global_objects/function/tosource/index.html deleted file mode 100644 index 32a43d0da2..0000000000 --- a/files/vi/web/javascript/reference/global_objects/function/tosource/index.html +++ /dev/null @@ -1,65 +0,0 @@ ---- -title: Function.prototype.toSource() -slug: Web/JavaScript/Reference/Global_Objects/Function/toSource -translation_of: Web/JavaScript/Reference/Global_Objects/Function/toSource ---- -
{{JSRef}} {{non-standard_header}}
- -

Phương pháp toSource() trả về một chuỗi đại diện cho mã nguồn của đối tượng.

- -

Cú pháp

- -
function.toSource();
-
- -

Giá trị trả về

- -

Một chuỗi đại diện cho mã nguồn của đối tượng.

- -

Mô tả

- -

Phương pháp toSource trả về các giá trị theo

- - - -

Phương pháp này thường được gọi cục bộ trong Javascript và không rõ ràng bằng mã. Bạn có thể gọi toSource() trong khi gỡ lỗi để kiểm tra nội dung của một đối tượng.

- -

Đặc điểm chi tiết

- -

Không phải là một đặc tính chuẩn nào. Ghi rõ trong JavaScript 1.3.

- -

Trình duyệt tương thích

- -
- - -

{{Compat("javascript.builtins.Function.toSource")}}

-
- -

Liên quan

- - diff --git a/files/vi/web/javascript/reference/global_objects/generator/index.html b/files/vi/web/javascript/reference/global_objects/generator/index.html deleted file mode 100644 index a1ed3ecf07..0000000000 --- a/files/vi/web/javascript/reference/global_objects/generator/index.html +++ /dev/null @@ -1,130 +0,0 @@ ---- -title: Generator -slug: Web/JavaScript/Reference/Global_Objects/Generator -translation_of: Web/JavaScript/Reference/Global_Objects/Generator ---- -
{{JSRef}}
- -

Generator là một object return bởi một {{jsxref("Statements/function*", "generator function", "", 1)}}, nó phù hợp với cả iterable protocol và iterator protocol.

- -

Cú pháp

- -
function* gen() {
-  yield 1;
-  yield 2;
-  yield 3;
-}
-
-var g = gen(); // "Generator { }"
- -

Phương thức

- -
-
{{jsxref("Generator.prototype.next()")}}
-
Trả về giá trị yielded, được khai báo qua câu lệnh {{jsxref("Operators/yield", "yield")}}.
-
{{jsxref("Generator.prototype.return()")}}
-
Trả về giá trị và kết thúc generator.
-
{{jsxref("Generator.prototype.throw()")}}
-
Quăng lỗi vào generator (đồng thời kết thúc generator, trừ khi được bắt lại trong generator đó).
-
- -

Ví dụ

- -

Một vòng lặp vô hạn

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

Generator object cũ

- -

Firefox (SpiderMonkey) đã hiện thực phiên bản generators đầu tiên trong JavaScript 1.7, lúc đó dấu sao (*) trong khai báo không bắt buộc (bạn chỉ cần dùng từ khóa yield bên trong hàm). Tuy nhiên, kiểu viết này đã không còn được hổ trợ từ Firefox 58 (released ngày 23, tháng 1, 2018) ({{bug(1083482)}}).

- -

Các phương thức generator cũ

- -
-
Generator.prototype.next() {{non-standard_inline}}
-
Returns a value yielded by the {{jsxref("Operators/yield", "yield")}} expression. This corresponds to next() in the ES2015 generator object.
-
Generator.prototype.close() {{non-standard_inline}}
-
Closes the generator, so that when calling next() an {{jsxref("StopIteration")}} error will be thrown. This corresponds to the return() method in the ES2015 generator object.
-
Generator.prototype.send() {{non-standard_inline}}
-
Used to send a value to a generator. The value is returned from the {{jsxref("Operators/yield", "yield")}} expression, and returns a value yielded by the next {{jsxref("Operators/yield", "yield")}} expression. send(x) corresponds to next(x) in the ES2015 generator object.
-
Generator.prototype.throw() {{non-standard_inline}}
-
Throws an error to a generator. This corresponds to the throw() method in the ES2015 generator object.
-
- -

Legacy generator example

- -
function fibonacci() {
-  var a = yield 1;
-  yield a * 2;
-}
-
-var it = fibonacci();
-console.log(it);          // "Generator {  }"
-console.log(it.next());   // 1
-console.log(it.send(10)); // 20
-console.log(it.close());  // undefined
-console.log(it.next());   // throws StopIteration (as the generator is now closed)
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-generator-objects', 'Generator objects')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-generator-objects', 'Generator objects')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hổ trợ

- - - -

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

- -

Xem thêm

- -

Legacy generators

- - - -

ES2015 generators

- - diff --git a/files/vi/web/javascript/reference/global_objects/index.html b/files/vi/web/javascript/reference/global_objects/index.html deleted file mode 100644 index 58625d24b9..0000000000 --- a/files/vi/web/javascript/reference/global_objects/index.html +++ /dev/null @@ -1,203 +0,0 @@ ---- -title: Standard built-in objects -slug: Web/JavaScript/Reference/Global_Objects -tags: - - JavaScript - - NeedsTranslation - - Objects - - Reference - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects ---- -
{{jsSidebar("Objects")}}
- -

Chương này bao gồm các chuẩn của JavaScript, đối tượng tích hợp, gồm phương thức và thuộc tính của chúng.

- -

Thuật ngữ "đối tượng toàn cục" (hay đối tượng tích hợp chuẩn) ở đây không bị nhầm lẫn với đối tượng toàn cục. Ở đây, các đối tượng toàn cục đề cập đến các đối tượng trong phạm vi toàn cục. Bản thân đối tượng toàn cục cũng có thể được truy cập bằng toán tử: {{JSxRef("Toán tử/this", "this")}} trong toàn cục (nhưng chỉ khi ECMAScript 5 không được sử dụng; trong trường hợp đó, nó trả về: {{JSxRef("undefined")}}). Trong thực tế, phạm vi toàn cục bao gồm các thuộc tính của đối tượng toàn cục, các thuộc tính được kế thừa (nếu có).

- -
-

Các đối tượng khác trong phạm vi toàn cục cũng được tạo bởi tập lệnh từ người dùng (created by the user script) hoặc được cung cấp bởi các ứng dụng máy chủ. Các đối tượng mà máy chủ có sẵn trong trình duyệt được ghi lại trong tài liệu tham khảo API (API reference). Để biết thêm thông tin về sự khác biệt giữa DOM và JavaScript Core, hãy xem JavaScript technologies overview.

- -

Đối tượng chuẩn theo thể loại

- -

Các thuộc tính của giá trị

- -

Những đặc tính toàn cục này trả về một giá trị đơn giản; chúng không có thuộc tính hay phương thức nào.

- - - -

Các thuộc tính chức năng

- -

Các hàm toàn cục (gọi trên toàn cục chứ không phải trên một đối tượng) trực tiếp trả về kết quả cho người gọi.

- - - -

Các đối tượng cơ bản

- -

Đây là những đối tượng cơ bản mà tất cả các đối tượng các đều dựa vào. Nó bao gồm đối tượng đại diện cho các đối tượng, hàm, và lỗi chung.

- - - -

Số và ngày 

- -

Đây là các đối tượng cơ sở đại diện cho số, ngày, và các phép toán học.

- - - -

Xử lí văn bản

- -

Những đối tượng này đại diện cho chuỗi và hỗ trợ thao tác chúng.

- -

{{jsxref("String")}}

- - - -

Mục lục các bộ sưu tập

- -

Các đối tượng này đại diện cho các bộ sưu tập dữ liệu sắp xếp theo giá trị. Chúng bao gồm các mảng và cấu trúc mảng.

- - - -

Bộ sưu tập khóa

- -

Các đối tượng này đại diện cho các bộ sưu tập sử dụng với khóa; chúng chứa các phần tử lặp đi lặp lại theo thứ tự chèn.

- - - -

Cấu trúc dữ liệu

- -

Các đối tượng này đại diện và tương tác với các bộ đệm cấu trúc dữ liệu và dữ liệu được mã hóa bởi JavaScript Object Notation (JSON).

- - - - - - - -

Kiểm soát các đối tượng trừu tượng

- - - - - - - -

Sự phản 

- - - -

Quốc tế hóa

- -

Bổ sung vào ECMAScript Core các chức năng phát hiện ngôn ng

- - - - - - - -

WebAssembly

- - - - - - - -

Khác

- - - - - - -
diff --git a/files/vi/web/javascript/reference/global_objects/infinity/index.html b/files/vi/web/javascript/reference/global_objects/infinity/index.html deleted file mode 100644 index 73e388b0d1..0000000000 --- a/files/vi/web/javascript/reference/global_objects/infinity/index.html +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Infinity -slug: Web/JavaScript/Reference/Global_Objects/Infinity -translation_of: Web/JavaScript/Reference/Global_Objects/Infinity ---- -
{{jsSidebar("Objects")}}
- -

Thuộc tính global Infinity là giá trị kiểu số biểu diễn vô cùng.

- -

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

- -
{{EmbedInteractiveExample("pages/js/globalprops-infinity.html")}}
- - - -

Cú pháp

- -
Infinity 
- -

Mô tả

- -

Infinity là một thuộc tính của global object, hay nói các khác, là một biến trong global scope.

- -

Giá trị khởi đầu của Infinity là {{jsxref("Number.POSITIVE_INFINITY")}}. Giá trị Infinity (dương vô cùng) lớn hơn mọi số. Về mặt toán học, giá trị này có biểu hiện giống hệt với vô cùng; chẳng hạn, mọi số dương nhân với Infinity đều bằng Infinity, và mọi số chia cho Infinity đều bằng 0.

- -

Như đã định nghĩa trong bản đặc tả ECMAScript 5, Infinity là chỉ-đọc (cài đặt trong JavaScript 1.8.5 / Firefox 4).

- -

Ví dụ

- -
console.log(Infinity          ); /* Infinity */
-console.log(Infinity + 1      ); /* Infinity */
-console.log(Math.pow(10, 1000)); /* Infinity */
-console.log(Math.log(0)       ); /* -Infinity */
-console.log(1 / Infinity      ); /* 0 */
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa lần đầu. Cài đặt trong JavaScript 1.3
{{SpecName('ES5.1', '#sec-15.1.1.2', 'Infinity')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-value-properties-of-the-global-object-infinity', 'Infinity')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-value-properties-of-the-global-object-infinity', 'Infinity')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- - - -

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

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/isfinite/index.html b/files/vi/web/javascript/reference/global_objects/isfinite/index.html deleted file mode 100644 index a846d37172..0000000000 --- a/files/vi/web/javascript/reference/global_objects/isfinite/index.html +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: isFinite() -slug: Web/JavaScript/Reference/Global_Objects/isFinite -translation_of: Web/JavaScript/Reference/Global_Objects/isFinite ---- -
{{jsSidebar("Objects")}}
- -

Hàm global isFinite() xác định liệu giá trị truyền vào có phải một giá trị hữu hạn hay không. Nếu cần thiết, tham số sẽ được ép kiểu sang số trước.

- -
{{EmbedInteractiveExample("pages/js/globalprops-isfinite.html")}}
- - - -

Cú pháp

- -
isFinite(testValue)
- -

Tham số

- -
-
testValue
-
Giá trị để kiểm tra tính hữu hạn.
-
- -

Giá trị trả về

- -

false nếu đối số là dương hoặc âm {{jsxref("Infinity")}} hay là {{jsxref("NaN")}}; ngoài ra thì trả về true.

- -

Mô tả

- -

isFinite là hàm top-level và không liên kết với bất cứ object nào.

- -

Bạn có thể dùng hàm này để xác định liệu một số có phải là hữu hạn hay không. Hàm isFinite kiểm tra giá trị kiểu số truyền trong đối số của nó. Nếu đối số của nó là NaN, dương vô cùng, hoặc âm vô cùng, phương thức này trả về false; ngoài ra, nó trả về true.

- -

Ví dụ

- -
isFinite(Infinity);  // false
-isFinite(NaN);       // false
-isFinite(-Infinity); // false
-
-isFinite(0);         // true
-isFinite(2e64);      // true
-isFinite(910);       // true
-
-isFinite(null);      // true, sẽ trả về false với phương thức
-                     // chuyên biệt hơn Number.isFinite(null)
-
-isFinite('0');       // true, sẽ trả về false với phương thức
-                     // chuyên biệt hơn Number.isFinite("0")
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES3')}}{{Spec2('ES3')}}Định nghĩa lần đầu.
{{SpecName('ES5.1', '#sec-15.1.2.5', 'isFinite')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-isfinite-number', 'isFinite')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-isfinite-number', 'isFinite')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- - - -

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

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/json/index.html b/files/vi/web/javascript/reference/global_objects/json/index.html deleted file mode 100644 index 513e41e3ae..0000000000 --- a/files/vi/web/javascript/reference/global_objects/json/index.html +++ /dev/null @@ -1,132 +0,0 @@ ---- -title: JSON -slug: Web/JavaScript/Reference/Global_Objects/JSON -translation_of: Web/JavaScript/Reference/Global_Objects/JSON ---- -
{{JSRef}}
- -

JSON object chứa các phương thức để phân giải JavaScript Object Notation ({{glossary("JSON")}}) và chuyển hóa các giá trị sang JSON. Nó có thể được called, hoặc constructed, và aside từ 2 phương thức thuộc tính của nó, nó tự bản thân lại không có chức năng thú vị nào.

- -

Khác nhau giữa JavaScript and JSON

- -

JSON là một cú pháp để serializing các object, array, number, string, boolean và {{jsxref("null")}}. Nó dựa trên cú pháp JavaScript nhưng lại khác biệt với JavaScript: một số JavaScript không phải là JSON.

- -
-
Objects và Arrays
-
Các tên thuộc tính phải được đặt trong nháy kép; dấu phẩy kéo đuôi trailing commas sẽ không được chấp nhận.
-
Numbers
-
Các số 0 nằm ở đầu sẽ bị cấm. Một dấu chấm thập phân phải được theo sau bởi ít nhất một chữ số. NaN và Infinity cũng không được hỗ trợ.
-
Bất kỳ JSON text nào cũng là một biểu thức JavaScript hợp lệ...
-
...Nhưng chỉ có các JavaScript engines mà đã từng triển khai proposal để làm làm tất cả JSON text hợp lệ ECMA-262. Trong các engines mà không triển khai proposal, U+2028 LINE SEPARATOR và U+2029 PARAGRAPH SEPARATOR được cho phép trong các string literals và các property keys trong JSON; nhưng việc sử dụng chúng trong các tính năng này trong các JavaScript string literal sẽ gây ra {{jsxref("SyntaxError")}}.
-
- -

Consider this example where {{jsxref("JSON.parse()")}} parses the string as JSON and eval executes the string as JavaScript:

- -
let code = '"\u2028\u2029"'
-JSON.parse(code)  // evaluates to "\u2028\u2029" in all engines
-eval(code)        // throws a SyntaxError in old engines
-
- -

Other differences include allowing only double-quoted strings and having no provisions for {{jsxref("undefined")}} or comments. For those who wish to use a more human-friendly configuration format based on JSON, there is JSON5, used by the Babel compiler, and the more commonly used YAML.

- -

Cú pháp JSON đầy đủ

- -

Cú pháp JSON đầy đủ như sau:

- -
JSON = null
-    or true or false
-    or JSONNumber
-    or JSONString
-    or JSONObject
-    or JSONArray
-
-JSONNumber = - PositiveNumber
-          or PositiveNumber
-PositiveNumber = DecimalNumber
-              or DecimalNumber . Digits
-              or DecimalNumber . Digits ExponentPart
-              or DecimalNumber ExponentPart
-DecimalNumber = 0
-             or OneToNine Digits
-ExponentPart = e Exponent
-            or E Exponent
-Exponent = Digits
-        or + Digits
-        or - Digits
-Digits = Digit
-      or Digits Digit
-Digit = 0 through 9
-OneToNine = 1 through 9
-
-JSONString = ""
-          or " StringCharacters "
-StringCharacters = StringCharacter
-                or StringCharacters StringCharacter
-StringCharacter = any character
-                  except " or \ or U+0000 through U+001F
-               or EscapeSequence
-EscapeSequence = \" or \/ or \\ or \b or \f or \n or \r or \t
-              or \u HexDigit HexDigit HexDigit HexDigit
-HexDigit = 0 through 9
-        or A through F
-        or a through f
-
-JSONObject = { }
-          or { Members }
-Members = JSONString : JSON
-       or Members , JSONString : JSON
-
-JSONArray = [ ]
-         or [ ArrayElements ]
-ArrayElements = JSON
-             or ArrayElements , JSON
-
- -

Các khoảng trắng lớn có thể hiện diện ở bất cứ đâu ngoại trừ bên trong một JSONnumber (các số không được chứa khoảng trắng nào) hoặc JSONString (nơi mà nó được interpreted như là một ký tự tương ứng trong một chuỗi, hoặc sẽ gây ra lỗi). Ký tự tab (U+0009), carriage return (U+000D), line feed (U+000A), and space (U+0020) là những ký tự khoảng trắng duy nhất hợp lệ.

- -

Methods

- -
-
{{jsxref("JSON.parse()", "JSON.parse(text[, reviver])")}}
-
Phân giải chuỗi text dưới dạng JSON, tùy chọn thêm việc chuyển hóa giá trị được tạo ra và các thuộc tính của nó, sau đó return giá trị. Bất kì sự vi phạm nào về cú pháp JSON, kể cả những trường hợp liên quan đến sự khác nhau giữa JavaScript và JSON, sẽ dấn đến một {{jsxref("SyntaxError")}} được thrown. Lựa chọn reviver cho phép interpreting những gì mà replacer sử dụng để đại diện cho các kiểu dữ liệu khác.
-
{{jsxref("JSON.stringify()", "JSON.stringify(value[, replacer[, space]])")}}
-
Return một chuỗi JSON tương ứng với giá trị được chỉ định, tùy chọn thêm việc bao gồm chỉ các thuộc tính nhất định hoặc thay thế giá trị thuộc tính theo cách user định nghĩa. Mặc định, tất cả các instances của {{jsxref("undefined")}} sẽ được thay thế bằng {{jsxref("null")}}, và các kiểu dữ liệu native không được hỗ trợ khác sẽ bị kiểm duyệt. Tùy chọn replacer cho phép chỉ định các cách thực thi khác.
-
- -

Specifications

- - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-json-object', 'JSON')}}
- -

Browser compatibility

- -
-
- - -

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

-
-
- -

See also

- - - -

Tools

- - diff --git a/files/vi/web/javascript/reference/global_objects/map/index.html b/files/vi/web/javascript/reference/global_objects/map/index.html deleted file mode 100644 index 45be246c96..0000000000 --- a/files/vi/web/javascript/reference/global_objects/map/index.html +++ /dev/null @@ -1,263 +0,0 @@ ---- -title: Map -slug: Web/JavaScript/Reference/Global_Objects/Map -tags: - - ES6 - - JavaScript - - Map - - cách dùng - - hàm -translation_of: Web/JavaScript/Reference/Global_Objects/Map ---- -
{{JSRef}}
- -

Đối tượng Map lưu cặp key-value (khoá - giá trị) theo thứ tự chèn vào của khoá. Bất kỳ giá trị nào (cả đối tượng (objects) và {{Glossary("Primitive", "primitive values")}}) đều có thể sử dụng làm key hoặc value.

- -

Cú pháp

- -
new Map([iterable])
- -

Tham số

- -
-
iterable
-
Một {{jsxref("Array")}} hoặc iterable object có các phần tử là cặp key-value (các mảng có 2 phần tử, vd. [[ 1, 'one' ],[ 2, 'two' ]]). Mỗi cặp key-value sẽ được thêm vào Map mới; những giá trị null chuyển thành undefined.
-
- -

Mô tả

- -

Một Map object duyệt qua các phần tử của nó theo thứ tự chèn vào –– một vòng lặp {{jsxref("Statements/for...of", "for...of")}} trả về một mảng [key, value] cho mỗi lần lặp.

- -

Key equality (so sánh key)

- -

Key được xác định bằng nhau dựa vào giải thuật "SameValueZero": NaN được xem là giống NaN (mặc dù NaN !== NaN) và tất cả các giá trị khác được xem xét bằng nhau theo toán tử ===. Trong đặc tả ECMAScript hiện tại, -0+0 là bằng nhau, cho dù điều này không đúng ở các bản dự thảo trước đó. Xem "Value equality for -0 and 0" trong bảng tương thích trình duyệt để biết thêm chi tiết.

- -

Objects and maps compared

- -

{{jsxref("Object", "Objects")}} tương tự với Maps ở chỗ cả hai đều cho phép bạn đặt keys cho values, lấy các values, xoá các keys và xem có gì được chứa trong một key không. Bởi vì điều này (và bởi vì trước đây không tích hợp các lựa chọn khác), trong lịch sử, Objects đã được dùng như Maps; Tuy vậy, có những điểm khác biệt khiến sử dụng một Map thích hợp hơn trong các trường hợp nhất định: 

- - - -

Các thuộc tính

- -
-
Map.length
-
Giá trị của thuộc tính length là 0.
-
Để lấy số phần tử đang có trong mảng, sử dụng {{jsxref("Map.prototype.size")}}.
-
{{jsxref("Map.@@species", "get Map[@@species]")}}
-
The constructor function that is used to create derived objects.
-
{{jsxref("Map.prototype")}}
-
Represents the prototype for the Map constructor. Allows the addition of properties to all Map objects.
-
- -

Map instances

- -

?Tất cả Map instances kế thừa từ {{jsxref("Map.prototype")}}.

- -

Các thuộc tính

- -

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

- -

Các phương thức

- -

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

- -

?Ví dụ

- -

Sử dụng Map object

- -
var myMap = new Map();
-
-var keyString = 'a string',
-    keyObj = {},
-    keyFunc = function() {};
-
-// đặt các values
-myMap.set(keyString, "value associated with 'a string'");
-myMap.set(keyObj, 'value associated with keyObj');
-myMap.set(keyFunc, 'value associated with keyFunc');
-
-myMap.size; // 3
-
-// lấy các values
-myMap.get(keyString);    // "value associated with 'a string'"
-myMap.get(keyObj);       // "value associated with keyObj"
-myMap.get(keyFunc);      // "value associated with keyFunc"
-
-myMap.get('a string');   // "value associated with 'a string'"
-                         // ?vì keyString === 'a string'
-myMap.get({});           // undefined, vì keyObj !== {}
-myMap.get(function() {}) // undefined, vì  keyFunc !== function () {}
-
- -

Sử dụng NaN làm Map keys

- -

NaN có thể sử dụng làm một key. Kể cả khi mỗi NaN không bằng chính nó (NaN !== NaN trả về true), ví dụ sau chạy tốt bởi vì các NaNs không phân biệt lẫn nhau:

- -
var myMap = new Map();
-myMap.set(NaN, 'not a number');
-
-myMap.get(NaN); // "not a number"
-
-var otherNaN = Number('foo');
-myMap.get(otherNaN); // "not a number"
-
- -

Duyệt Maps với for..of

- -

Maps có thể được duyệt với vòng lặp for..of:

- -
var myMap = new Map();
-myMap.set(0, 'zero');
-myMap.set(1, 'one');
-for (var [key, value] of myMap) {
-  console.log(key + ' = ' + value);
-}
-// 0 = zero
-// 1 = one
-
-for (var key of myMap.keys()) {
-  console.log(key);
-}
-// 0
-// 1
-
-for (var value of myMap.values()) {
-  console.log(value);
-}
-// zero
-// one
-
-for (var [key, value] of myMap.entries()) {
-  console.log(key + ' = ' + value);
-}
-// 0 = zero
-// 1 = one
-
- -

Duyệt Maps với forEach()

- -

Maps có thể được duyệt bằng phương thức forEach():

- -
myMap.forEach(function(value, key) {
-  console.log(key + ' = ' + value);
-});
-// Will show 2 logs; first with "0 = zero" and second with "1 = one"
-
- -

Quan hệ với Array objects

- -
var kvArray = [['key1', 'value1'], ['key2', 'value2']];
-
-// Sử dụng hàm khởi tạo Map để chuyển một 2D key-value Array vào một map
-var myMap = new Map(kvArray);
-
-myMap.get('key1'); // returns "value1"
-
-// Sử dụng hàm Array.from để chuyển một map vào một 2D key-value Array
-console.log(Array.from(myMap)); // Sẽ hiện ra Array giống hệt kvArray
-
-// Hoặc sử dụng duyệt keys hoặc values và chuyển chúng thành một mảng
-console.log(Array.from(myMap.keys())); // Sẽ hiện ["key1", "key2"]
-
- -

Nhân bản (cloning) và gộp (merging) Maps

- -

Giống như Arrays, Maps có thể được nhân bản:

- -
var original = new Map([
-  [1, 'one']
-]);
-
-var clone = new Map(original);
-
-console.log(clone.get(1)); // one
-console.log(original === clone); // false. Useful for shallow comparison
- -

Keep in mind that the data itself is not cloned

- -

Maps có thể được gộp lại, vẫn đảm bảo các key là duy nhất: 

- -
var first = new Map([
-  [1, 'one'],
-  [2, 'two'],
-  [3, 'three'],
-]);
-
-var second = new Map([
-  [1, 'uno'],
-  [2, 'dos']
-]);
-
-// Merge two maps. The last repeated key wins.
-// Spread operator essentially converts a Map to an Array
-var merged = new Map([...first, ...second]);
-
-console.log(merged.get(1)); // uno
-console.log(merged.get(2)); // dos
-console.log(merged.get(3)); // three
- -

Maps cũng có thể được gộp với Arrays:

- -
var first = new Map([
-  [1, 'one'],
-  [2, 'two'],
-  [3, 'three'],
-]);
-
-var second = new Map([
-  [1, 'uno'],
-  [2, 'dos']
-]);
-
-// Merge maps with an array. The last repeated key wins.
-var merged = new Map([...first, ...second, [1, 'eins']]);
-
-console.log(merged.get(1)); // eins
-console.log(merged.get(2)); // dos
-console.log(merged.get(3)); // three
- -

Các đặc tả

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-map-objects', 'Map')}}{{Spec2('ES2015')}}Initial definition.
{{SpecName('ESDraft', '#sec-map-objects', 'Map')}}{{Spec2('ESDraft')}} 
- -

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

- - - -

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

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/math/abs/index.html b/files/vi/web/javascript/reference/global_objects/math/abs/index.html deleted file mode 100644 index 94c4b859e8..0000000000 --- a/files/vi/web/javascript/reference/global_objects/math/abs/index.html +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: Math.abs() -slug: Web/JavaScript/Reference/Global_Objects/Math/abs -tags: - - JavaScript - - Math - - Phương Thức - - Tham khảo -translation_of: Web/JavaScript/Reference/Global_Objects/Math/abs ---- -
{{JSRef}}
- -

Hàm Math.abs() trả về giá trị tuyệt đối của một số như sau

- -

Math.abs(x)=|x|={xifx>00ifx=0-xifx<0{\mathtt{\operatorname{Math.abs}(z)}} = {|z|} = \begin{cases} x & \text{if} \quad x \geq 0 \\ x & \text{if} \quad x < 0 \end{cases}

- -
{{EmbedInteractiveExample("pages/js/math-abs.html")}}
- - - -

Cú pháp

- -
Math.abs(x)
- -

Tham số

- -
-
x
-
Loại số liệu.
-
- -

Giá trị trả về

- -

Giá trị tuyệt đối của số đã cho.

- -

Mô tả

- -

 

- -

Do abs() là phương thức tĩnh của Math, nên ta phải khai báo là Math.abs(), thay vì dùng nó như 1 phương thức của đối tượng được tạo ra từ Math (Math không phải hàm tạo).

- -

 

- -

Ví dụ

- -

Hành vi của Math.abs()

- -

Truyền một đối tượng rỗng, một mảng có hơn một giá trị, một chuỗi ký tự không-có-số hay một {{jsxref("undefined")}}/biến rỗng sẽ trả về {{jsxref("NaN")}}. Truyền {{jsxref("null")}}, một chuỗi rỗng hay một mảng rỗng sẽ trả về số 0.

- -
Math.abs('-1');     // 1
-Math.abs(-2);       // 2
-Math.abs(null);     // 0
-Math.abs('');       // 0
-Math.abs([]);       // 0
-Math.abs([2]);      // 2
-Math.abs([1,2]);    // NaN
-Math.abs({});       // NaN
-Math.abs('string'); // NaN
-Math.abs();         // NaN
-
- -

Thông số kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Thông số kỹ thuậtTrạng tháiChú thích
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa đầu tiên. Được đưa vào JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.1', 'Math.abs')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.abs', 'Math.abs')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.abs', 'Math.abs')}}{{Spec2('ESDraft')}} 
- -

Tính tương thích trên trình duyệt

- - - -

{{Compat("javascript.builtins.Math.abs")}}

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/math/ceil/index.html b/files/vi/web/javascript/reference/global_objects/math/ceil/index.html deleted file mode 100644 index 09b056af36..0000000000 --- a/files/vi/web/javascript/reference/global_objects/math/ceil/index.html +++ /dev/null @@ -1,172 +0,0 @@ ---- -title: Math.ceil() -slug: Web/JavaScript/Reference/Global_Objects/Math/ceil -tags: - - JavaScript - - Math - - Phương Thức - - Tham khảo -translation_of: Web/JavaScript/Reference/Global_Objects/Math/ceil ---- -
{{JSRef}}
- -

Hàm Math.ceil() trả về số nguyên nhỏ nhất có giá trị lớn hơn hoặc bằng số đã cho.

- -

Lưu ý: Math.ceil({{jsxref("null")}}) trả về số nguyên 0 và không đưa ra lỗi {{jsxref("NaN")}}.

- -
{{EmbedInteractiveExample("pages/js/math-ceil.html")}}
- - - -

Cú pháp

- -
Math.ceil(x)
- -

Tham số

- -
-
x
-
Loại số liệu.
-
- -

Giá trị trả về

- -

Số nguyên nhỏ nhất có giá trị lớn hơn hoặc bằng số đã cho (bằng tham số).

- -

Mô tả

- -

Do ceil() là phương thức tĩnh của Math, nên ta phải khai báo là Math.ceil(), thay vì dùng nó như 1 phương thức của đối tượng được tạo ra từ Math (Math không phải hàm tạo).

- -

Ví dụ

- -

Cách dùng Math.ceil()

- -

Ví dụ sau minh họa cách dùng Math.ceil() điển hình.

- -
Math.ceil(.95);    // 1
-Math.ceil(4);      // 4
-Math.ceil(7.004);  // 8
-Math.ceil(-0.95);  // -0
-Math.ceil(-4);     // -4
-Math.ceil(-7.004); // -7
-
- -

Tinh chỉ số thập phân

- -
// Đóng kín
-(function() {
-  /**
-   * Tinh chỉ số thập phân của một con số.
-   *
-   * @param {String}  type  Loại điều chỉnh.
-   * @param {Number}  value Số liệu.
-   * @param {Integer} exp   Số mũ (the 10 logarithm of the adjustment base).
-   * @returns {Number} Giá trị đã chỉnh sửa.
-   */
-  function decimalAdjust(type, value, exp) {
-    // Nếu exp có giá trị undefined hoặc bằng không thì...
-    if (typeof exp === 'undefined' || +exp === 0) {
-      return Math[type](value);
-    }
-    value = +value;
-    exp = +exp;
-    // Nếu value không phải là ố hoặc exp không phải là số nguyên thì...
-    if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
-      return NaN;
-    }
-    // Shift
-    value = value.toString().split('e');
-    value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
-    // Shift back
-    value = value.toString().split('e');
-    return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
-  }
-
-  // Làm tròn số thập phân (theo mốc số 5)
-  if (!Math.round10) {
-    Math.round10 = function(value, exp) {
-      return decimalAdjust('round', value, exp);
-    };
-  }
-  // Làm tròn số thập phân (về gần giá trị 0)
-  if (!Math.floor10) {
-    Math.floor10 = function(value, exp) {
-      return decimalAdjust('floor', value, exp);
-    };
-  }
-  // Làm tròn số thập phân (ra xa giá trị 0)
-  if (!Math.ceil10) {
-    Math.ceil10 = function(value, exp) {
-      return decimalAdjust('ceil', value, exp);
-    };
-  }
-})();
-
-// Chạy hàm round
-Math.round10(55.55, -1);   // 55.6
-Math.round10(55.549, -1);  // 55.5
-Math.round10(55, 1);       // 60
-Math.round10(54.9, 1);     // 50
-Math.round10(-55.55, -1);  // -55.5
-Math.round10(-55.551, -1); // -55.6
-Math.round10(-55, 1);      // -50
-Math.round10(-55.1, 1);    // -60
-// Chạy hàm floor
-Math.floor10(55.59, -1);   // 55.5
-Math.floor10(59, 1);       // 50
-Math.floor10(-55.51, -1);  // -55.6
-Math.floor10(-51, 1);      // -60
-// Chạy hàm ceil
-Math.ceil10(55.51, -1);    // 55.6
-Math.ceil10(51, 1);        // 60
-Math.ceil10(-55.59, -1);   // -55.5
-Math.ceil10(-59, 1);       // -50
-
- -

Thông số kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Thông số kỹ thuậtTrạng tháiChú thích
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa đầu tiên được đưa vào JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.6', 'Math.ceil')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math.ceil', 'Math.ceil')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-math.ceil', 'Math.ceil')}}{{Spec2('ESDraft')}} 
- -

Tính tương thích trên trình duyệt

- - - -

{{Compat("javascript.builtins.Math.ceil")}}

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/math/floor/index.html b/files/vi/web/javascript/reference/global_objects/math/floor/index.html deleted file mode 100644 index 2f660fcf00..0000000000 --- a/files/vi/web/javascript/reference/global_objects/math/floor/index.html +++ /dev/null @@ -1,132 +0,0 @@ ---- -title: Math.floor() -slug: Web/JavaScript/Reference/Global_Objects/Math/floor -translation_of: Web/JavaScript/Reference/Global_Objects/Math/floor ---- -
{{JSRef}}
- -

Hàm Math.floor() trả về số nguyên bé hơn hoặc bằng số ban đầu.

- -
{{EmbedInteractiveExample("pages/js/math-floor.html")}}
- - - -

Cú pháp

- -
Math.floor(x)
- -

Tham số

- -
-
x
-
Một số.
-
- -

Giá trị trả về

- -

Số nguyên lớn nhất nhỏ hơn hoặc bằng số đã cho.

- -

Mô tả

- -

Bởi vì floor() là một phương thức tĩnh của Math, bạn luôn sử dụng Math.floor(), thay vì sử dụng như là một phương thức của đối tượng được tạo ra từ Math (Math không phải là một constructor).

- -
-

Lưu ý: Math.floor(null) trả về 0, không phải {{jsxref("NaN")}}.

-
- -

Ví dụ

- -

Sử dụng Math.floor()

- -
Math.floor( 45.95); //  45
-Math.floor( 45.05); //  45
-Math.floor(  4   ); //   4
-Math.floor(-45.05); // -46
-Math.floor(-45.95); // -46
-
- -

Điều chỉnh thập phân

- -
/**
- * Decimal adjustment of a number.
- *
- * @param {String}  type  The type of adjustment.
- * @param {Number}  value The number.
- * @param {Integer} exp   The exponent (the 10 logarithm of the adjustment base).
- * @returns {Number} The adjusted value.
- */
-function decimalAdjust(type, value, exp) {
-  // If the exp is undefined or zero...
-  if (typeof exp === 'undefined' || +exp === 0) {
-    return Math[type](value);
-  }
-  value = +value;
-  exp = +exp;
-  // If the value is not a number or the exp is not an integer...
-  if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
-    return NaN;
-  }
-  // Shift
-  value = value.toString().split('e');
-  value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
-  // Shift back
-  value = value.toString().split('e');
-  return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
-}
-
-// Decimal round
-const round10 = (value, exp) => decimalAdjust('round', value, exp);
-// Decimal floor
-const floor10 = (value, exp) => decimalAdjust('floor', value, exp);
-// Decimal ceil
-const ceil10 = (value, exp) => decimalAdjust('ceil', value, exp);
-
-// Round
-round10(55.55, -1);   // 55.6
-round10(55.549, -1);  // 55.5
-round10(55, 1);       // 60
-round10(54.9, 1);     // 50
-round10(-55.55, -1);  // -55.5
-round10(-55.551, -1); // -55.6
-round10(-55, 1);      // -50
-round10(-55.1, 1);    // -60
-// Floor
-floor10(55.59, -1);   // 55.5
-floor10(59, 1);       // 50
-floor10(-55.51, -1);  // -55.6
-floor10(-51, 1);      // -60
-// Ceil
-ceil10(55.51, -1);    // 55.6
-ceil10(51, 1);        // 60
-ceil10(-55.59, -1);   // -55.5
-ceil10(-59, 1);       // -50
-
- -

Quy cách kỹ thuật

- - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-math.floor', 'Math.floor')}}
- -

Trình duyệt tương thích

- - - -

{{Compat("javascript.builtins.Math.floor")}}

- -

Xem thêm:

- - diff --git a/files/vi/web/javascript/reference/global_objects/math/index.html b/files/vi/web/javascript/reference/global_objects/math/index.html deleted file mode 100644 index bfaa405142..0000000000 --- a/files/vi/web/javascript/reference/global_objects/math/index.html +++ /dev/null @@ -1,196 +0,0 @@ ---- -title: Math -slug: Web/JavaScript/Reference/Global_Objects/Math -tags: - - JavaScript - - Math - - NeedsTranslation - - Reference - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Math ---- -
{{JSRef}}
- -

Math is a built-in object that has properties and methods for mathematical constants and functions. Not a function object.

- -

Description

- -

Unlike the other global objects, Math is not a constructor. All properties and methods of Math are static. You refer to the constant pi as Math.PI and you call the sine function as Math.sin(x), where x is the method's argument. Constants are defined with the full precision of real numbers in JavaScript.

- -

Properties

- -
-
{{jsxref("Math.E")}}
-
Euler's constant and the base of natural logarithms, approximately 2.718.
-
{{jsxref("Math.LN2")}}
-
Natural logarithm of 2, approximately 0.693.
-
{{jsxref("Math.LN10")}}
-
Natural logarithm of 10, approximately 2.303.
-
{{jsxref("Math.LOG2E")}}
-
Base 2 logarithm of E, approximately 1.443.
-
{{jsxref("Math.LOG10E")}}
-
Base 10 logarithm of E, approximately 0.434.
-
{{jsxref("Math.PI")}}
-
Ratio of the circumference of a circle to its diameter, approximately 3.14159.
-
{{jsxref("Math.SQRT1_2")}}
-
Square root of 1/2; equivalently, 1 over the square root of 2, approximately 0.707.
-
{{jsxref("Math.SQRT2")}}
-
Square root of 2, approximately 1.414.
-
- -

Methods

- -
-

Note that the trigonometric functions (sin(), cos(), tan(), asin(), acos(), atan(), atan2()) expect or return angles in radians. To convert radians to degrees, divide by (Math.PI / 180), and multiply by this to convert the other way.

-
- -
-

Note that many math functions have a precision that's implementation-dependent. This means that different browsers can give a different result, and even the same JS engine on a different OS or architecture can give different results.

-
- -
-
{{jsxref("Global_Objects/Math/abs", "Math.abs(x)")}}
-
Returns the absolute value of a number.
-
{{jsxref("Global_Objects/Math/acos", "Math.acos(x)")}}
-
Returns the arccosine of a number.
-
{{jsxref("Global_Objects/Math/acosh", "Math.acosh(x)")}}
-
Returns the hyperbolic arccosine of a number.
-
{{jsxref("Global_Objects/Math/asin", "Math.asin(x)")}}
-
Returns the arcsine of a number.
-
{{jsxref("Global_Objects/Math/asinh", "Math.asinh(x)")}}
-
Returns the hyperbolic arcsine of a number.
-
{{jsxref("Global_Objects/Math/atan", "Math.atan(x)")}}
-
Returns the arctangent of a number.
-
{{jsxref("Global_Objects/Math/atanh", "Math.atanh(x)")}}
-
Returns the hyperbolic arctangent of a number.
-
{{jsxref("Global_Objects/Math/atan2", "Math.atan2(y, x)")}}
-
Returns the arctangent of the quotient of its arguments.
-
{{jsxref("Global_Objects/Math/cbrt", "Math.cbrt(x)")}}
-
Returns the cube root of a number.
-
{{jsxref("Global_Objects/Math/ceil", "Math.ceil(x)")}}
-
Returns the smallest integer greater than or equal to a number.
-
{{jsxref("Global_Objects/Math/clz32", "Math.clz32(x)")}}
-
Returns the number of leading zeroes of a 32-bit integer.
-
{{jsxref("Global_Objects/Math/cos", "Math.cos(x)")}}
-
Returns the cosine of a number.
-
{{jsxref("Global_Objects/Math/cosh", "Math.cosh(x)")}}
-
Returns the hyperbolic cosine of a number.
-
{{jsxref("Global_Objects/Math/exp", "Math.exp(x)")}}
-
Returns Ex, where x is the argument, and E is Euler's constant (2.718…), the base of the natural logarithm.
-
{{jsxref("Global_Objects/Math/expm1", "Math.expm1(x)")}}
-
Returns subtracting 1 from exp(x).
-
{{jsxref("Global_Objects/Math/floor", "Math.floor(x)")}}
-
Returns the largest integer less than or equal to a number.
-
{{jsxref("Global_Objects/Math/fround", "Math.fround(x)")}}
-
Returns the nearest single precision float representation of a number.
-
{{jsxref("Global_Objects/Math/hypot", "Math.hypot([x[, y[, …]]])")}}
-
Returns the square root of the sum of squares of its arguments.
-
{{jsxref("Global_Objects/Math/imul", "Math.imul(x, y)")}}
-
Returns the result of a 32-bit integer multiplication.
-
{{jsxref("Global_Objects/Math/log", "Math.log(x)")}}
-
Returns the natural logarithm (loge, also ln) of a number.
-
{{jsxref("Global_Objects/Math/log1p", "Math.log1p(x)")}}
-
Returns the natural logarithm (loge, also ln) of 1 + x for a number x.
-
{{jsxref("Global_Objects/Math/log10", "Math.log10(x)")}}
-
Returns the base 10 logarithm of a number.
-
{{jsxref("Global_Objects/Math/log2", "Math.log2(x)")}}
-
Returns the base 2 logarithm of a number.
-
{{jsxref("Global_Objects/Math/max", "Math.max([x[, y[, …]]])")}}
-
Returns the largest of zero or more numbers.
-
{{jsxref("Global_Objects/Math/min", "Math.min([x[, y[, …]]])")}}
-
Returns the smallest of zero or more numbers.
-
{{jsxref("Global_Objects/Math/pow", "Math.pow(x, y)")}}
-
Returns base to the exponent power, that is, baseexponent.
-
{{jsxref("Global_Objects/Math/random", "Math.random()")}}
-
Returns a pseudo-random number between 0 and 1.
-
{{jsxref("Global_Objects/Math/round", "Math.round(x)")}}
-
Returns the value of a number rounded to the nearest integer.
-
{{jsxref("Global_Objects/Math/sign", "Math.sign(x)")}}
-
Returns the sign of the x, indicating whether x is positive, negative or zero.
-
{{jsxref("Global_Objects/Math/sin", "Math.sin(x)")}}
-
Returns the sine of a number.
-
{{jsxref("Global_Objects/Math/sinh", "Math.sinh(x)")}}
-
Returns the hyperbolic sine of a number.
-
{{jsxref("Global_Objects/Math/sqrt", "Math.sqrt(x)")}}
-
Returns the positive square root of a number.
-
{{jsxref("Global_Objects/Math/tan", "Math.tan(x)")}}
-
Returns the tangent of a number.
-
{{jsxref("Global_Objects/Math/tanh", "Math.tanh(x)")}}
-
Returns the hyperbolic tangent of a number.
-
Math.toSource() {{non-standard_inline}}
-
Returns the string "Math".
-
{{jsxref("Global_Objects/Math/trunc", "Math.trunc(x)")}}
-
Returns the integer part of the number x, removing any fractional digits.
-
- -

Extending the Math object

- -

As with most of the built-in objects in JavaScript, the Math object can be extended with custom properties and methods. To extend the Math object, you do not use prototype. Instead, you directly extend Math:

- -
Math.propName = propValue;
-Math.methodName = methodRef;
- -

For instance, the following example adds a method to the Math object for calculating the greatest common divisor of a list of arguments.

- -
/* Variadic function -- Returns the greatest common divisor of a list of arguments */
-Math.gcd = function() {
-    if (arguments.length == 2) {
-        if (arguments[1] == 0)
-            return arguments[0];
-        else
-            return Math.gcd(arguments[1], arguments[0] % arguments[1]);
-    } else if (arguments.length > 2) {
-        var result = Math.gcd(arguments[0], arguments[1]);
-        for (var i = 2; i < arguments.length; i++)
-            result = Math.gcd(result, arguments[i]);
-        return result;
-    }
-};
- -

Try it:

- -
console.log(Math.gcd(20, 30, 15, 70, 40)); // `5`
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.8', 'Math')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-math-object', 'Math')}}{{Spec2('ES6')}}New methods {{jsxref("Math.log10()", "log10()")}}, {{jsxref("Math.log2()", "log2()")}}, {{jsxref("Math.log1p()", "log1p()")}}, {{jsxref("Math.expm1()", "expm1()")}}, {{jsxref("Math.cosh()", "cosh()")}}, {{jsxref("Math.sinh()", "sinh()")}}, {{jsxref("Math.tanh()", "tanh()")}}, {{jsxref("Math.acosh()", "acosh()")}}, {{jsxref("Math.asinh()", "asinh()")}}, {{jsxref("Math.atanh()", "atanh()")}}, {{jsxref("Math.hypot()", "hypot()")}}, {{jsxref("Math.trunc()", "trunc()")}}, {{jsxref("Math.sign()", "sign()")}}, {{jsxref("Math.imul()", "imul()")}}, {{jsxref("Math.fround()", "fround()")}}, {{jsxref("Math.cbrt()", "cbrt()")}} and {{jsxref("Math.clz32()", "clz32()")}} added.
{{SpecName('ESDraft', '#sec-math-object', 'Math')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- - - -

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

- -

See also

- - diff --git a/files/vi/web/javascript/reference/global_objects/math/sqrt/index.html b/files/vi/web/javascript/reference/global_objects/math/sqrt/index.html deleted file mode 100644 index cefbcccb04..0000000000 --- a/files/vi/web/javascript/reference/global_objects/math/sqrt/index.html +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Math.sqrt() -slug: Web/JavaScript/Reference/Global_Objects/Math/sqrt -tags: - - JavaScript - - Math - - Phương Thức - - Tham khảo - - Toán -translation_of: Web/JavaScript/Reference/Global_Objects/Math/sqrt ---- -
{{JSRef}}
- -

Hàm Math.sqrt() trả về giá trị căn bậc hai, that is

- -

x0,Math.sqrt(x)=x=trị tuyệt đối củay0tương ứngy2=x\forall x \geq 0, \mathtt{Math.sqrt(x)} = \sqrt{x} = \text{the unique} \; y \geq 0 \; \text{such that} \; y^2 = x

- -
{{EmbedInteractiveExample("pages/js/math-sqrt.html")}}
- - - -

Cú pháp

- -
Math.sqrt(x)
- -

Tham số

- -
-
x
-
Một con số
-
- -

Giá trị trả về

- -

Căn bậc hai của số cung cấp. Nếu hàm nhận giá trị, {{jsxref("NaN")}} sẽ bị trả về.

- -

Mô tả

- -

Nếu x là con số âm, Math.sqrt() sẽ trả về {{jsxref("NaN")}}.

- -

Do sqrt() là phương thức tĩnh của Math, ta phải dùng theo cách này Math.sqrt(), thay vì dùng dưới dạng phương thức của đối tượng Math mà bạn tạo ra (Math không phải là một hàm khởi tạo, constructor).

- -

Ví dụ

- -

Dùng Math.sqrt()

- -
Math.sqrt(9); // 3
-Math.sqrt(2); // 1.414213562373095
-
-Math.sqrt(1);  // 1
-Math.sqrt(0);  // 0
-Math.sqrt(-1); // NaN
-Math.sqrt(-0); // -0
-
- -

Thông số kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Thông số kỹ thuậtTrạng tháiChú thích
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa lần đầu. Tích hợp trong JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.8.2.17', 'Math.sqrt')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-math.sqrt', 'Math.sqrt')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-math.sqrt', 'Math.sqrt')}}{{Spec2('ESDraft')}}
- -

Tính tương thích trên trình duyệt

- - - -

{{Compat("javascript.builtins.Math.sqrt")}}

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/nan/index.html b/files/vi/web/javascript/reference/global_objects/nan/index.html deleted file mode 100644 index cf7be92a59..0000000000 --- a/files/vi/web/javascript/reference/global_objects/nan/index.html +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: NaN -slug: Web/JavaScript/Reference/Global_Objects/NaN -tags: - - JavaScript - - Tham khảo - - Thuộc tính -translation_of: Web/JavaScript/Reference/Global_Objects/NaN ---- -
{{jsSidebar("Objects")}}
- -

Thuộc tính global NaN có giá trị đại diện cho khái niệm Not-A-Number (Không-phải-Số).

- -

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

- -
{{EmbedInteractiveExample("pages/js/globalprops-nan.html")}}
- - - -

Cú pháp

- -
NaN
- -

Mô tả

- -

NaN là thuộc tính của đối tượng global.

- -

Giá trị khởi tạo của NaN là Not-A-Number — giống như giá trị của {{jsxref("Number.NaN")}}. Với các trình duyệt hiện đại, NaN không thể cấu hình được, không có thuộc tính được-viết. Kể cả khi được phép thì vẫn phải tránh việc ghi đè lên nó.

- -

Người ta hiếm khi dùng NaN trong viết chương trình. Nó được dùng làm giá trị trả về khi việc tính toán của các hàm {{jsxref("Math")}} thất bại (Math.sqrt(-1)) hoặc khi hàm phân tích phải dữ liệu số sai (parseInt("là lá la")).

- -

Kiểm thử phép so sánh NaN

- -

Không thể thực hiện phép so sánh bằng (thông qua ==, !=, ===, và !==NaN với bất kỳ giá trị nào khác, bao gồm cả một giá trị NaN khác. Hãy dùng {{jsxref("Number.isNaN()")}} hoặc {{jsxref("Global_Objects/isNaN", "isNaN()")}} để xác định rõ ràng đó có phải là NaN hay không. Hoặc làm thử một phép so sánh bản thân: NaN, và chỉ NaN, sẽ so sánh không cân bằng với chính nó.

- -
NaN === NaN;        // false (sai)
-Number.NaN === NaN; // false
-isNaN(NaN);         // true (đúng)
-isNaN(Number.NaN);  // true
-
-function valueIsNaN(v) { return v !== v; }
-valueIsNaN(1);          // false
-valueIsNaN(NaN);        // true
-valueIsNaN(Number.NaN); // true
-
- -

Tuy nhiên, lưu ý rằng có khác biệt giữa isNaN() và Number.isNaN(): isNaN() sẽ trả về giá trị true (đúng) nếu như giá trị hiện tại là NaN hoặc nó sẽ thành NaN sau khi bị ép số hóa dữ liệu, còn với Number.isNaN() thì dữ liệu trả về là true chỉ khi giá trị hiện tại là NaN.

- -
isNaN('hello world'); // trả về giá trị 'true'.
-Number.isNaN('hello world'); // trả về giá trị 'false'.
-
- -

Thông số kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Thông số kỹ thuậtTrạng tháiChú thích
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa đầu tiên. Được đưa vào JavaScript 1.3
{{SpecName('ES5.1', '#sec-15.1.1.1', 'NaN')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-value-properties-of-the-global-object-nan', 'NaN')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-value-properties-of-the-global-object-nan', 'NaN')}}{{Spec2('ESDraft')}} 
- -

Tính tương thích trên trình duyệt

- - - -

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

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/number/index.html b/files/vi/web/javascript/reference/global_objects/number/index.html deleted file mode 100644 index 24b3e1b756..0000000000 --- a/files/vi/web/javascript/reference/global_objects/number/index.html +++ /dev/null @@ -1,216 +0,0 @@ ---- -title: Number -slug: Web/JavaScript/Reference/Global_Objects/Number -tags: - - JavaScript - - Number - - Reference - - Vietnamese -translation_of: Web/JavaScript/Reference/Global_Objects/Number ---- -
{{JSRef}}
- -

Đối tượng JavaScript Number là một đối tượng bao bọc cho phép bạn làm việc với các giá trị số. Một đối tượng Number có thể được tạo ra sử dụng hàm khởi tạo Number().

- -

Cú pháp

- -
new Number(value);
- -

Các tham số

- -
-
value
-
Giá trị số của đối tượng được tạo ra.
-
- -

Mô tả

- -

Các sử dụng chính cho đối tượng Number là:

- - - -

Các thuộc tính

- -
-
{{jsxref("Number.EPSILON")}}
-
Khoảng cách nhỏ nhất giữa hai số có thể biểu thị được.
-
{{jsxref("Number.MAX_SAFE_INTEGER")}}
-
Các số an toàn tối đa trong JavaScript (253 - 1)
-
{{jsxref("Number.MAX_VALUE")}}
-
Đại diện cho giá trị số lớn nhất.
-
{{jsxref("Number.MIN_SAFE_INTEGER")}}
-
Các số an toàn tối thiểu trong JavaScript (-(253 - 1)).
-
{{jsxref("Number.MIN_VALUE")}}
-
Đại diện cho giá trị số nhỏ nhất - nghĩa là số dương gần với không nhất (không thực sự bằng không).
-
{{jsxref("Number.NaN")}}
-
Giá trị đặc biệt "không phải là một số".
-
{{jsxref("Number.NEGATIVE_INFINITY")}}
-
Giá trị đặc biệt đại diện cho âm vô cùng; được trả về khi tràn.
-
{{jsxref("Number.POSITIVE_INFINITY")}}
-
Giá trị đặc biệt đại diện cho dương vô cùng; được trả về khi tràn.
-
{{jsxref("Number.prototype")}}
-
-

Cho phép thêm các thuộc tính cho đối tượng Number

-
-
- -

Các phương thức

- -
-
{{jsxref("Number.isNaN()")}}
-
Xác định giá trị được truyền là NaN.
-
{{jsxref("Number.isFinite()")}}
-
Xác định giá trị được truyền là một số hữu hạn.
-
{{jsxref("Number.isInteger()")}}
-
Xác định giá trị được truyền là một số nguyên.
-
{{jsxref("Number.isSafeInteger()")}}
-
Xác định giá trị được truyền là một số an toàn (số giữa -(253 - 1) và 253 - 1).
-
{{jsxref("Number.toInteger()")}} {{obsolete_inline}}
-
Được sử dụng để đánh giá giá trị được truyền và chuyển đổi nó sang một số nguyên (or {{jsxref("Global_Objects/Infinity", "Infinity")}}), nhưng đã được loại bỏ.
-
{{jsxref("Number.parseFloat()")}}
-
Giá trị cũng giống như {{jsxref("parseFloat", "parseFloat()")}} của đối tượng toàn cầu.
-
{{jsxref("Number.parseInt()")}}
-
Giá trị cũng giống như {{jsxref("parseInt", "parseInt()")}} của đối tượng toàn cầu.
-
- -

Các thể hiện của Number

- -

Tất cả các thể hiện của Number được kế thừa từ {{jsxref("Number.prototype")}}. Các đối tượng nguyên mẫu (prototype) của hàm khởi tạo Number có thể được sửa đổi để ảnh hưởng đến tất cả các thể hiện của Number.

- -

Các ví dụ

- -

Sử dụng đối tượng Number để gán các giá trị cho các biến số.

- -

Ví dụ sau sử dụng các thuộc tính của đối tượng Number để gán các giá trị cho các biến số khác nhau:

- -
var biggestNum = Number.MAX_VALUE;
-var smallestNum = Number.MIN_VALUE;
-var infiniteNum = Number.POSITIVE_INFINITY;
-var negInfiniteNum = Number.NEGATIVE_INFINITY;
-var notANum = Number.NaN;
- -

Phạm vi số nguyên của Number

- -

Ví dụ sau cho thấy các giá trị số nguyên tối thiểu và tối đa có thể được biểu diễn dưới dạng đối tượng Number:

- -
var biggestInt = 9007199254740992;
-var smallestInt = -9007199254740992;
-
- -

Khi phân tích cú pháp dữ liệu đã được tuần tự hóa thành JSON, các giá trị số nguyên vượt ra khỏi phạm vi này có thể được dự kiến sẽ bị hỏng khi trình phân tích cú pháp JSON ép buộc chúng với kiểu Số. Sử dụng {{jsxref ("String")}} thay vào đó là một giải pháp khả thi.

- -

Sử dụng Number để chuyển đổi một đối tượng Date

- -

Ví dụ sau chuyển đổi một đối tượng {{jsxref("Date")}} sang một giá trị số sử dụng Number như là một hàm:

- -
var d = new Date('October 30, 1996 13:46:36');
-console.log(Number(d));
-
- -

Kết quả: 846657996000.

- -

Chuyển đổi chuỗi dạng số sang số

- -
Number("123")     // 123
-Number("")        // 0
-Number("   ")     // 0
-Number("0x11")    // 17
-Number("0b11")    // 3
-Number("0o11")    // 9
-Number("foo")     // NaN
-Number("100a")    // NaN
-
- -

Thông số kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc điểm kỹ thuậtTrạng tháiChú thích
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa ban đầu. Được thực hiện trong JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7', 'Number')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number-objects', 'Number')}}{{Spec2('ES6')}}Đã thêm các phương pháp và thuộc tính mới: {{jsxref("Number.EPSILON", "EPSILON")}}, {{jsxref("Number.isFinite", "isFinite")}}, {{jsxref("Number.isInteger", "isInteger")}}, {{jsxref("Number.isNaN", "isNaN")}}, {{jsxref("Number.parseFloat", "parseFloat")}}, {{jsxref("Number.parseInt", "parseInt")}}
{{SpecName('ESDraft', '#sec-number-objects', 'Number')}}{{Spec2('ESDraft')}} 
- -

Khả năng tương thích trình duyệt

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
Đặc tínhChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
Đặc tínhAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/number/isfinite/index.html b/files/vi/web/javascript/reference/global_objects/number/isfinite/index.html deleted file mode 100644 index 907227aa76..0000000000 --- a/files/vi/web/javascript/reference/global_objects/number/isfinite/index.html +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: Number.isFinite() -slug: Web/JavaScript/Reference/Global_Objects/Number/isFinite -translation_of: Web/JavaScript/Reference/Global_Objects/Number/isFinite ---- -
{{JSRef}}
- -

Phương thức Number.isFinite() xác định liệu giá trị truyền vào có phải một giá trị hữu hạn hay không.

- -
{{EmbedInteractiveExample("pages/js/number-isfinite.html")}}
- - - -

Cú pháp

- -
Number.isFinite(value)
- -

Tham số

- -
-
value
-
Giá trị để kiểm tra tính hữu hạn.
-
- -

Giá trị trả về

- -

Giá trị {{jsxref("Boolean")}} cho biết liệu giá trị truyền vào có phải hữu hạn hay không.

- -

Mô tả

- -

So sánh với hàm global {{jsxref("isFinite", "isFinite()")}}, phương thức này không ép kiểu tham số truyền vào thành kiểu số. Nghĩa là chỉ những giá trị có kiểu số, đồng thời có giá trị hữu hạn, mới trả về true.

- -

Ví dụ

- -
Number.isFinite(Infinity);  // false
-Number.isFinite(NaN);       // false
-Number.isFinite(-Infinity); // false
-
-Number.isFinite(0);         // true
-Number.isFinite(2e64);      // true
-
-Number.isFinite('0');       // false, sẽ thành true nếu dùng
-                            // global isFinite('0')
-Number.isFinite(null);      // false, sẽ thành true nếu dùng
-                            // global isFinite(null)
-
- -

Polyfill

- -
if (Number.isFinite === undefined) Number.isFinite = function(value) {
-    return typeof value === 'number' && isFinite(value);
-}
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES6', '#sec-number.isfinite', 'Number.isInteger')}}{{Spec2('ES6')}}Định nghĩa lần đầu.
{{SpecName('ESDraft', '#sec-number.isfinite', 'Number.isInteger')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- - - -

{{Compat("javascript.builtins.Number.isFinite")}}

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/number/isinteger/index.html b/files/vi/web/javascript/reference/global_objects/number/isinteger/index.html deleted file mode 100644 index 522ff1945a..0000000000 --- a/files/vi/web/javascript/reference/global_objects/number/isinteger/index.html +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: Number.isInteger() -slug: Web/JavaScript/Reference/Global_Objects/Number/isInteger -tags: - - JavaScript - - Method - - Number - - Reference -translation_of: Web/JavaScript/Reference/Global_Objects/Number/isInteger ---- -
{{JSRef}}
- -

Phương thức Number.isInteger() xác định xem giá trị truyền vô có phải là một integer hay không.

- -

Cú pháp

- -
Number.isInteger(value)
- -

Parameters

- -
-
value
-
Giá trị cần kiểm tra xem nó có phải là một integer hay không.
-
- -

Mô tả

- -

Nếu giá trị mà bạn truyền vô trong phương thức này là một integer, kết quả trả về sẽ là true, ngược lại thì trả về false. Nếu giá trị đó là {{jsxref("NaN")}} hoặc các giá trị Infinity thì đương nhiên vẫn trả về false.

- -

Các ví dụ

- -
Number.isInteger(0);         // true
-Number.isInteger(1);         // true
-Number.isInteger(-100000);   // true
-
-Number.isInteger(0.1);       // false
-Number.isInteger(Math.PI);   // false
-
-Number.isInteger(Infinity);  // false
-Number.isInteger(-Infinity); // false
-Number.isInteger("10");      // false
-Number.isInteger(true);      // false
-Number.isInteger(false);     // false
-Number.isInteger([1]);       // false
-
- -

Polyfill

- -
Number.isInteger = Number.isInteger || function(value) {
-  return typeof value === "number" &&
-    isFinite(value) &&
-    Math.floor(value) === value;
-};
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-number.isinteger', 'Number.isInteger')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-number.isinteger', 'Number.isInteger')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- -

{{Compat("javascript.builtins.Number.isInteger")}}

- -
 
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/number/isnan/index.html b/files/vi/web/javascript/reference/global_objects/number/isnan/index.html deleted file mode 100644 index a4497d6dae..0000000000 --- a/files/vi/web/javascript/reference/global_objects/number/isnan/index.html +++ /dev/null @@ -1,99 +0,0 @@ ---- -title: Number.isNaN() -slug: Web/JavaScript/Reference/Global_Objects/Number/isNaN -tags: - - ECMAScript 2015 - - JavaScript - - Method - - Number -translation_of: Web/JavaScript/Reference/Global_Objects/Number/isNaN ---- -
{{JSRef}}
- -

Phương thức Number.isNaN() (NaN viết tắt cho Not a Number) xác định xem giá trị đó có chính xác là {{jsxref("NaN")}} hay không. Một phiên bản khác của phương thức này, nhưng nằm trong phạm vi global đó là: {{jsxref("isNaN", "isNaN()")}}.

- -

Cú pháp

- -
Number.isNaN(value)
- -

Parameters

- -
-
value
-
Giá trị truyền vô để kiểm tra xem nó có phải chính xác là {{jsxref("NaN")}} hay không.
-
- -

Mô tả

- -

Cả hai phương pháp operator so sánh bằng, đó là {{jsxref("Operators/Comparison_Operators", "==", "#Equality")}} và {{jsxref("Operators/Comparison_Operators", "===", "#Identity")}} đề trả ra false khi chúng ta kiểm tra giá trị {{jsxref("NaN")}} {{jsxref("NaN")}} ví dụ: NaN === NaN, (đáng lẽ ra là true đúng không ?, nhưng thực tế giá trị NaN này không thể được xác định bằng cách này.), phương thức Number.isNaN() được tạo ra để làm việc này. Phương pháp này đưa ra 1 giải pháp để xác định NaN, NaN là một giá trị mà không thể so sánh với chính nó để kiểm tra như các giá trị khác trong JavaScript.

- -

{{jsxref("isNaN", "isNaN()")}} là phương thức kiểm tra NaN trong phạm vi global, lưu ý là Number.isNaN() không giống như isNaN() trong global, Number.isNaN() xác định chính xác {{jsxref("NaN")}} đó có phải là giá trị {{jsxref("NaN")}} của Number hay không. Vì, chỉ có NaN thật sự mới đưa ra được giá trị true khi mang vô phương thức này. Khác với global, miễn cái gì không phải là số thì cũng trả ra giá trị là true.

- -

Các ví dụ

- -
Number.isNaN(NaN);        // true
-Number.isNaN(Number.NaN); // true
-Number.isNaN(0 / 0)       // true
-
-// e.g. these would have been true with global isNaN()
-Number.isNaN("NaN");      // false
-Number.isNaN(undefined);  // false
-Number.isNaN({});         // false
-Number.isNaN("blabla");   // false
-
-// These all return false
-Number.isNaN(true);
-Number.isNaN(null);
-Number.isNaN(37);
-Number.isNaN("37");
-Number.isNaN("37.37");
-Number.isNaN("");
-Number.isNaN(" ");
-
- -

Polyfill

- -
Number.isNaN = Number.isNaN || function(value) {
-    return typeof value === "number" && isNaN(value);
-}
-
-// Or
-Number.isNaN = Number.isNaN || function(value) {
-    return value !== value;
-}
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-number.isnan', 'Number.isnan')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-number.isnan', 'Number.isnan')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
{{Compat("javascript.builtins.Number.isNaN")}}
- -
 
- -

See also

- - diff --git a/files/vi/web/javascript/reference/global_objects/number/issafeinteger/index.html b/files/vi/web/javascript/reference/global_objects/number/issafeinteger/index.html deleted file mode 100644 index f49bf8d30e..0000000000 --- a/files/vi/web/javascript/reference/global_objects/number/issafeinteger/index.html +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: Number.isSafeInteger() -slug: Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger -translation_of: Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger ---- -
{{JSRef}}
- -

Phương thức Number.isSafeInteger() xác định xem giá trị truyền vào có phải một số nằm trong khoảng của số nguyên an toàn hay không.

- -
{{EmbedInteractiveExample("pages/js/number-issafeinteger.html")}}
- - - -

Số nguyên an toàn là số nguyên mà

- - - -

Chẳng hạn, 253 - 1 là một số nguyên an toàn: nó có thể hiển thị chính xác, và không có số nguyên nào có thể làm tròn đến nó với bất cứ chế độ làm tròn theo chuẩn IEEE-754. Ngoài ra, 253 không phải là một số nguyên an toàn: nó có thể được biểu diễn chính xác theo chuẩn IEEE-754, nhưng số nguyên 253 + 1 không thể hiển thị chính xác theo chuẩn IEEE-754 mà thay vào đó được làm tròn về 253 theo kiểu làm tròn về số gần nhất và làm tròn về không. Số nguyên an toàn nằm trong đoạn từ -(253 - 1) đến 253 - 19007199254740991hoặc ±9,007,199,254,740,991).

- -

Xử lý giá trị lớn hơn hoặc nhỏ hơn ~9 triệu tỉ với độ chính xác toàn vẹn yêu cầu sử dụng thư viện số học độ chính xác bất kì. Xem What Every Programmer Needs to Know about Floating Point Arithmetic để biết thêm thông tin về cách biểu diễn số thực dấu phẩy động.

- -

Cú pháp

- -
Number.isSafeInteger(testValue)
-
- -

Tham số

- -
-
testValue
-
Giá trị để kiểm tra có phải số nguyên an toàn hay không.
-
- -

Giá trị trả về

- -

{{jsxref("Boolean")}} cho biết liệu giá trị truyền vào có phải là số nguyên an toàn hay không.

- -

Ví dụ

- -
Number.isSafeInteger(3);                    // true
-Number.isSafeInteger(Math.pow(2, 53));      // false
-Number.isSafeInteger(Math.pow(2, 53) - 1);  // true
-Number.isSafeInteger(NaN);                  // false
-Number.isSafeInteger(Infinity);             // false
-Number.isSafeInteger('3');                  // false
-Number.isSafeInteger(3.1);                  // false
-Number.isSafeInteger(3.0);                  // true
-
- -

Polyfill

- -
Number.isSafeInteger = Number.isSafeInteger || function (value) {
-   return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER;
-};
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES2015', '#sec-number.issafeinteger', 'Number.isSafeInteger')}}{{Spec2('ES2015')}}Định nghĩa lần đầu.
{{SpecName('ESDraft', '#sec-number.issafeinteger', 'Number.isSafeInteger')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- - - -

{{Compat("javascript.builtins.Number.isSafeInteger")}}

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/number/max_safe_integer/index.html b/files/vi/web/javascript/reference/global_objects/number/max_safe_integer/index.html deleted file mode 100644 index 7ae2ab0657..0000000000 --- a/files/vi/web/javascript/reference/global_objects/number/max_safe_integer/index.html +++ /dev/null @@ -1,71 +0,0 @@ ---- -title: Number.MAX_SAFE_INTEGER -slug: Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER -translation_of: Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER ---- -
{{JSRef}}
- -

Hằng Number.MAX_SAFE_INTEGER biểu diễn giá trị số nguyên an toàn lớn nhất trong JavaScript (253 - 1).

- -
{{EmbedInteractiveExample("pages/js/number-maxsafeinteger.html")}}
- - - -
{{js_property_attributes(0, 0, 0)}}
- -

Mô tả

- -

Hằng MAX_SAFE_INTEGER có giá trị là 9007199254740991(9,007,199,254,740,991 hay là ~9 triệu tỉ). Nguyên do đằng sau con số đó là do JavaScript sử dụng số thực dấu phẩy động độ chính xác kép được đặc tả trong chuẩn IEEE 754 và chỉ có thể biểu diễn an toàn các số trong khoảng -(253 - 1)253 - 1.

- -

An toàn trong ngữ cảnh này ám chỉ khả năng biểu diễn cũng như so sánh số nguyên một cách chính xác. Chẳng hạn,Number.MAX_SAFE_INTEGER+1 === Number.MAX_SAFE_INTEGER+2 sẽ trả về true, theo toán học thì là sai. Xem {{jsxref("Number.isSafeInteger()")}} để biết thêm chi tiết.

- -

Bởi vì MAX_SAFE_INTEGER là một thuộc tính tĩnh của {{jsxref("Number")}}, bạn thường dùng nó bằng Number.MAX_SAFE_INTEGER, thay vì tự tạo ra thuộc tính cho object {{jsxref("Number")}}.

- -

Ví dụ

- -
Number.MAX_SAFE_INTEGER // 9007199254740991
-Number.MAX_SAFE_INTEGER * Number.EPSILON // 2 bởi vì đối với số thực dấu phẩy động, giá trị thực tế chính là the decimal trailing "1"
-                                        // ngoại trừ trường hợp có độ chính xác subnormal như là zero (0)
-
- -

Polyfill

- -
if (!Number.MAX_SAFE_INTEGER) {
-    Number.MAX_SAFE_INTEGER = Math.pow(2, 53) - 1; // 9007199254740991
-}
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES2015', '#sec-number.max_safe_integer', 'Number.MAX_SAFE_INTEGER')}}{{Spec2('ES2015')}}Định nghĩa lần đầu.
{{SpecName('ESDraft', '#sec-number.max_safe_integer', 'Number.MAX_SAFE_INTEGER')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- - - -

{{Compat("javascript.builtins.Number.MAX_SAFE_INTEGER")}}

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/number/min_safe_integer/index.html b/files/vi/web/javascript/reference/global_objects/number/min_safe_integer/index.html deleted file mode 100644 index 4a3ecf1a76..0000000000 --- a/files/vi/web/javascript/reference/global_objects/number/min_safe_integer/index.html +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: Number.MIN_SAFE_INTEGER -slug: Web/JavaScript/Reference/Global_Objects/Number/MIN_SAFE_INTEGER -translation_of: Web/JavaScript/Reference/Global_Objects/Number/MIN_SAFE_INTEGER ---- -
{{JSRef}}
- -

The Number.MIN_SAFE_INTEGER biểu diễn giá trị số nguyên an toàn lớn nhất trong JavaScript (-(253 - 1)).

- -
{{EmbedInteractiveExample("pages/js/number-min-safe-integer.html")}}
- - - -
{{js_property_attributes(0, 0, 0)}}
- -

Mô tả

- -

Hằng MAX_SAFE_INTEGER có giá trị là -9007199254740991(-9,007,199,254,740,991 hay là khoảng âm 9 triệu tỉ). Nguyên do đằng sau con số đó là do JavaScript sử dụng số thực dấu phẩy động độ chính xác kép được đặc tả trong chuẩn IEEE 754 và chỉ có thể biểu diễn an toàn các số trong khoảng -(253 - 1)253 - 1. Xem {{jsxref("Number.isSafeInteger()")}} để biết thêm chi tiết.

- -

Bởi vì MIN_SAFE_INTEGER là một thuộc tính tĩnh của {{jsxref("Number")}}, bạn thường dùng nó bằng Number.MIN_SAFE_INTEGER, thay vì tự tạo ra thuộc tính cho object {{jsxref("Number")}}.

- -

Ví dụ

- -
Number.MIN_SAFE_INTEGER // -9007199254740991
--(Math.pow(2, 53) - 1)  // -9007199254740991
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES2015', '#sec-number.min_safe_integer', 'Number.MIN_SAFE_INTEGER')}}{{Spec2('ES2015')}}Định nghĩa lần đầu.
{{SpecName('ESDraft', '#sec-number.min_safe_integer', 'Number.MIN_SAFE_INTEGER')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- - - -

{{Compat("javascript.builtins.Number.MIN_SAFE_INTEGER")}}

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/number/nan/index.html b/files/vi/web/javascript/reference/global_objects/number/nan/index.html deleted file mode 100644 index daf2661d0a..0000000000 --- a/files/vi/web/javascript/reference/global_objects/number/nan/index.html +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: Number.NaN -slug: Web/JavaScript/Reference/Global_Objects/Number/NaN -tags: - - JavaScript - - Number - - Thuộc tính -translation_of: Web/JavaScript/Reference/Global_Objects/Number/NaN ---- -
{{JSRef}}
- -

Thuộc tính Number.NaN đại diện cho khái niệm Not-A-Number (Không-phải-Số). Tương đương với {{jsxref("NaN")}}.

- -
{{EmbedInteractiveExample("pages/js/number-nan.html")}}
- -

Ta không phải tạo đối tượng {{jsxref("Number")}} để truy cập vào thuộc tính tĩnh này (dùng cú pháp Number.NaN).

- -
{{js_property_attributes(0, 0, 0)}}
- -

Thông số kỹ thuật

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Thông số kỹ thuậtTrạng tháiChú thích
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa đầu tiên. Được đưa vào JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.7.3.4', 'Number.NaN')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.nan', 'Number.NaN')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-number.nan', 'Number.NaN')}}{{Spec2('ESDraft')}} 
- -

Tính tương thích trên trình duyệt

- - - -

{{Compat("javascript.builtins.Number.NaN")}}

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/number/negative_infinity/index.html b/files/vi/web/javascript/reference/global_objects/number/negative_infinity/index.html deleted file mode 100644 index 75e87a4657..0000000000 --- a/files/vi/web/javascript/reference/global_objects/number/negative_infinity/index.html +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Number.NEGATIVE_INFINITY -slug: Web/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY -translation_of: Web/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY ---- -
{{JSRef}}
- -

Thuộc tính Number.NEGATIVE_INFINITY biểu diễn giá trị âm của Infinity (âm vô cực).

- -
{{EmbedInteractiveExample("pages/js/number-negative-infinity.html")}}
- - - -

Bạn không cần tạo đối tượng {{jsxref("Number")}} để truy cập vào đối tượng này (hãy dùng Number.NEGATIVE_INFINITY).

- -
{{js_property_attributes(0, 0, 0)}}
- -

Mô tả

- -

Giá trị của Number.NEGATIVE_INFINITY cũng giống như giá trị âm của thuộc tính {{jsxref("Infinity")}} của global object.

- -

Giá trị này hành xử hơi khác so với âm vô cực trong toán học:

- - - -

Bạn có thể dùng thuộc tính Number.NEGATIVE_INFINITY để xác định điều kiện xem có trả về số hữu hạn hay không. Chú ý, ngoài ra, {{jsxref("isFinite")}} sẽ hợp với trường hợp này hơn.

- -

Ví dụ

- -

Sử dụng NEGATIVE_INFINITY

- -

Trong ví dụ sau đây, biến smallNumber được gán giá trị nhỏ hơn giá trị nhỏ nhất. Khi lệnh {{jsxref("Statements/if...else", "if")}} được thực thi, smallNumber có giá trị -Infinity, nên smallNumber được gán lại giá trị dễ kiểm soát hơn trước khi tiếp tục.

- -
var smallNumber = (-Number.MAX_VALUE) * 2;
-
-if (smallNumber === Number.NEGATIVE_INFINITY) {
-  smallNumber = returnFinite();
-}
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa lần đầu. Cài đặt trong JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.3.5', 'Number.NEGATIVE_INFINITY')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.negative_infinity', 'Number.NEGATIVE_INFINITY')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-number.negative_infinity', 'Number.NEGATIVE_INFINITY')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- - - -

{{Compat("javascript.builtins.Number.NEGATIVE_INFINITY")}}

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/number/positive_infinity/index.html b/files/vi/web/javascript/reference/global_objects/number/positive_infinity/index.html deleted file mode 100644 index 54b2db905e..0000000000 --- a/files/vi/web/javascript/reference/global_objects/number/positive_infinity/index.html +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Number.POSITIVE_INFINITY -slug: Web/JavaScript/Reference/Global_Objects/Number/POSITIVE_INFINITY -translation_of: Web/JavaScript/Reference/Global_Objects/Number/POSITIVE_INFINITY ---- -
{{JSRef}}
- -

Thuộc tính Number.POSITIVE_INFINITY biểu diễn giá trị dương Infinity (dương vô cùng).

- -
{{EmbedInteractiveExample("pages/js/number-positive-infinity.html")}}
- - - -

Bạn không cần tạo đối tượng{{jsxref("Number")}} để truy cập vào đối tượng này (hãy dùng Number.POSITIVE_INFINITY).

- -
{{js_property_attributes(0, 0, 0)}}
- -

Mô tả

- -

Giá trị của Number.POSITIVE_INFINITY cũng giống như giá trị dương của thuộc tính {{jsxref("Infinity")}} của global object.

- -

Giá trị này hành xử hơi khác so với vô cùng trong toán học:

- - - -

Bạn có thể dùng thuộc tính Number.POSITIVE_INFINITY để xác định điều kiện xem có trả về số hữu hạn hay không. Chú ý, ngoài ra, {{jsxref("isFinite")}} sẽ hợp với trường hợp này hơn.

- -

Ví dụ

- -

Sử dụng POSITIVE_INFINITY

- -

Trong ví dụ sau đây, biến bigNumber được gán giá trị lớn hơn giá trị lớn nhất. Khi lệnh {{jsxref("Statements/if...else", "if")}} được thực thi, bigNumber có giá trị Infinity, nên bigNumber được gán lại giá trị dễ kiểm soát hơn trước khi tiếp tục.

- -
var bigNumber = Number.MAX_VALUE * 2;
-
-if (bigNumber == Number.POSITIVE_INFINITY) {
-  bigNumber = returnFinite();
-}
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES1')}}{{Spec2('ES1')}}Định nghĩa lần đầu. Cài đặt trong JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.7.3.6', 'Number.POSITIVE_INFINITY')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-number.positive_infinity', 'Number.POSITIVE_INFINITY')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-number.positive_infinity', 'Number.POSITIVE_INFINITY')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- - - -

{{Compat("javascript.builtins.Number.POSITIVE_INFINITY")}}

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/object/assign/index.html b/files/vi/web/javascript/reference/global_objects/object/assign/index.html deleted file mode 100644 index 2f5b00f1ec..0000000000 --- a/files/vi/web/javascript/reference/global_objects/object/assign/index.html +++ /dev/null @@ -1,259 +0,0 @@ ---- -title: Object.assign() -slug: Web/JavaScript/Reference/Global_Objects/Object/assign -tags: - - JavaScript - - Method - - Object -translation_of: Web/JavaScript/Reference/Global_Objects/Object/assign ---- -
{{JSRef}}
- -

Object.assign() được sử dụng để sao chép các giá trị của tất cả thuộc tính có thể liệt kê từ một hoặc nhiều đối tượng nguồn đến một đối tượng đích. Nó sẽ  trả về đối tượng đích đó.

- -

{{EmbedInteractiveExample("pages/js/object-assign.html")}}

- -

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

- -

Cú pháp

- -
Object.assign(target, ...sources)
- -

Các tham số

- -
-
target
-
Đối tượng đích
-
sources
-
Các đối tượng nguồn
-
- -

Giá trị trả về

- -

(Các) Đối tượng đích

- -

Mô tả

- -

Các thuộc tính trong đối tượng đích sẽ bị ghi lại bởi các thuộc tính trong đối tượng nguồn nếu chúng có cùng key. Tương tự, các thuộc tính nguồn sau sẽ ghi đè lên những thuộc tính nguồn trước. 

- -

Phương thức Object.assign() chỉ sao chép những giá trị liệt kê được và và các thuộc tính của bản thân nó đến đối tượng đích. Nó sử dụng  [[Get]] trên nguồn và [[Set]] trên đích, vì vậy nó sẽ gọi các hàm getter và setter.  Vì lý do đó nó chỉ định thuộc tính so với việc chỉ sao chép hoặc xác đinh các thuộc tính mới. Điều này có thể khiến nó không phù hợp khi gộp các thuộc tính mới vào một nguyên mẫu (prototype) nếu các nguồn gộp chứa các getter. Để sao chép các thuộc tính xác định, bao gồm cả khả năng đếm được vào trong các nguyên mẫu thì nên sử dụng {{jsxref("Object.getOwnPropertyDescriptor()")}} và {{jsxref("Object.defineProperty()")}} để thay thế.

- -

Các thuộc tính {{jsxref("String")}} và {{jsxref("Symbol")}} đều được sao chép.

- -

Trong trường hợp có một lỗi, như việc một thuộc tính không được phép ghi đè, một  {{jsxref("TypeError")}}  sẽ sinh ra, và đối tượng đích có thể được thay đổi nếu có bất kỳ thuộc tính nào đã được thêm vào trước khi lỗi được sinh ra.

- -

Chú ý rằng Object.assign() không ném ra một {{jsxref("null")}} hoặc {{jsxref("undefined")}}.

- -

Ví dụ

- -

Sao chép một object

- -
var obj = { a: 1 };
-var copy = Object.assign({}, obj);
-console.log(copy); // { a: 1 }
-
- -

Cảnh báo về Deep Clone

- -

Với deep cloning, chúng ta cần sử dụng những lựa chọn khác khác bởi vì Object.assign() sao chép các giá trị thuộc tính. Nếu giá trị nguồn là tham chiếu đến một object,  nó chỉ sao chép gía trị tham chiếu đó. 

- -
function test() {
-  'use strict';
-
-  let a = { b: {c: 4} , d: { e: {f: 1} } };
-  let g = Object.assign({}, a);
-  let h = JSON.parse(JSON.stringify(a));
-  console.log(JSON.stringify(g.d)); // { e: { f: 1 } }
-  g.d.e = 32;
-  console.log('g.d.e set to 32.'); // g.d.e set to 32.
-  console.log(JSON.stringify(g)); // { b: { c: 4 }, d: { e: 32 } }
-  console.log(JSON.stringify(a)); // { b: { c: 4 }, d: { e: 32 } }
-  console.log(JSON.stringify(h)); // { b: { c: 4 }, d: { e: { f: 1 } } }
-  h.d.e = 54;
-  console.log('h.d.e set to 54.'); // h.d.e set to 54.
-  console.log(JSON.stringify(g)); // { b: { c: 4 }, d: { e: 32 } }
-  console.log(JSON.stringify(a)); // { b: { c: 4 }, d: { e: 32 } }
-  console.log(JSON.stringify(h)); // { b: { c: 4 }, d: { e: 54 } }
-}
-
-test();
- -

Gộp các object

- -
var o1 = { a: 1 };
-var o2 = { b: 2 };
-var o3 = { c: 3 };
-
-var obj = Object.assign(o1, o2, o3);
-console.log(obj); // { a: 1, b: 2, c: 3 }
-console.log(o1);  // { a: 1, b: 2, c: 3 }, object đích tự nó bị thay đổi.
- -

Gộp các đối tượng với cùng giá trị

- -
var o1 = { a: 1, b: 1, c: 1 };
-var o2 = { b: 2, c: 2 };
-var o3 = { c: 3 };
-
-var obj = Object.assign({}, o1, o2, o3);
-console.log(obj); // { a: 1, b: 2, c: 3 }
- -

Các giá trị được ghi đè bởi các đối tượng khác mà chúng có chung các thuộc tính sau đó theo thứ tự các tham số.

- -

Sao chép thuộc tính symbol-typed

- -
var o1 = { a: 1 };
-var o2 = { [Symbol('foo')]: 2 };
-
-var obj = Object.assign({}, o1, o2);
-console.log(obj); // { a : 1, [Symbol("foo")]: 2 } (cf. bug 1207182 trên Firefox)
-Object.getOwnPropertySymbols(obj); // [Symbol(foo)]
-
- -

Các thuộc tính trên chuỗi nguyên mẫu và các thuộc tính không có khả năng đếm được thì không thể sao chép. 

- -
var obj = Object.create({ foo: 1 }, { // foo ở trên mắt xích prototype của obj.
-  bar: {
-    value: 2  // bar chứa thuộc tính không liệt kê được.
-  },
-  baz: {
-    value: 3,
-    enumerable: true  // baz chứa thuộc tính liệt kê được.
-  }
-});
-
-var copy = Object.assign({}, obj);
-console.log(copy); // { baz: 3 }
-
- -

Các giá trị nguyên thủy sẽ được gói thành các đối tượng.

- -
var v1 = 'abc';
-var v2 = true;
-var v3 = 10;
-var v4 = Symbol('foo');
-
-var obj = Object.assign({}, v1, null, v2, undefined, v3, v4);
-// Sự nguyên bản sẽ bị gói lại, null và undefined sẽ bị bỏ qua.
-// Ghi chú,chỉ có string wrapper mới có thuộc tính liệt kê được.
-console.log(obj); // { "0": "a", "1": "b", "2": "c" }
-
- -

Các ngoại lệ sẽ làm gián đoạn quá trình sao chép.

- -
var target = Object.defineProperty({}, 'foo', {
-  value: 1,
-  writable: false
-}); // target.foo chỉ read-only
-
-Object.assign(target, { bar: 2 }, { foo2: 3, foo: 3, foo3: 3 }, { baz: 4 });
-// TypeError: "foo" là read-only
-// Trường hợp ngoại lệ được tạo ra khi gán target.foo
-
-console.log(target.bar);  // 2, nguồn thứ nhất được sao chép thành công
-console.log(target.foo2); // 3, đặc tính thứ nhất của nguồn thứ 2 được chép thành công.
-console.log(target.foo);  // 1, ngoại lệ được ném ra
-console.log(target.foo3); // undefined, phương thức gán đã hoàn tất, foo3 sẽ không bị sao chép
-console.log(target.baz);  // undefined, nguồn thứ ba cũng không bị sao chép
-
- -

Sao chép các trình truy cập (accessor)

- -
var obj = {
-  foo: 1,
-  get bar() {
-    return 2;
-  }
-};
-
-var copy = Object.assign({}, obj);
-console.log(copy);
-// { foo: 1, bar: 2 }, giá trị của copy.bar là giá trị return của getter của obj.bar.
-
-// Đây là function gán sao chép toàn bộ các mô tả.
-function completeAssign(target, ...sources) {
-  sources.forEach(source => {
-    let descriptors = Object.keys(source).reduce((descriptors, key) => {
-      descriptors[key] = Object.getOwnPropertyDescriptor(source, key);
-      return descriptors;
-    }, {});
-    // Mặc định thì Object.assign sao chép cả Symbol thống kê được luôn
-    Object.getOwnPropertySymbols(source).forEach(sym => {
-      let descriptor = Object.getOwnPropertyDescriptor(source, sym);
-      if (descriptor.enumerable) {
-        descriptors[sym] = descriptor;
-      }
-    });
-    Object.defineProperties(target, descriptors);
-  });
-  return target;
-}
-
-var copy = completeAssign({}, obj);
-console.log(copy);
-// { foo:1, get bar() { return 2 } }
-
- -

Polyfill

- -

 {{Glossary("Polyfill","polyfill")}}  không hỗ trợ các thuộc tính symbol, kể từ ES5 thì cũng không còn symbol nữa:

- -
if (typeof Object.assign != 'function') {
-  Object.assign = function(target, varArgs) { // .length của function là 2
-    'use strict';
-    if (target == null) { // TypeError nếu undefined hoặc null
-      throw new TypeError('Cannot convert undefined or null to object');
-    }
-
-    var to = Object(target);
-
-    for (var index = 1; index < arguments.length; index++) {
-      var nextSource = arguments[index];
-
-      if (nextSource != null) { // Bỏ qua nếu undefined hoặc null
-        for (var nextKey in nextSource) {
-          // Avoid bugs when hasOwnProperty is shadowed
-          if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
-            to[nextKey] = nextSource[nextKey];
-          }
-        }
-      }
-    }
-    return to;
-  };
-}
-
- -

Đặc tính kỹ thuật

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-object.assign', 'Object.assign')}}{{Spec2('ESDraft')}}
{{SpecName('ES2015', '#sec-object.assign', 'Object.assign')}}{{Spec2('ES2015')}}Initial definition.
- -

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

- -
{{Compat("javascript.builtins.Object.assign")}}
- -
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/object/defineproperties/index.html b/files/vi/web/javascript/reference/global_objects/object/defineproperties/index.html deleted file mode 100644 index c96b3f7527..0000000000 --- a/files/vi/web/javascript/reference/global_objects/object/defineproperties/index.html +++ /dev/null @@ -1,228 +0,0 @@ ---- -title: Object.defineProperties() -slug: Web/JavaScript/Reference/Global_Objects/Object/defineProperties -translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperties ---- -
{{JSRef}}
- -

Phương thức Object.defineProperties() định nghĩa hoặc thay đổi tức thì các thuộc tính của một đối tượng, sau đó trả lại đối tượng đó.

- -

Cú pháp

- -
Object.defineProperties(obj, props)
- -

Các tham số

- -
-
obj
-
Đối tượng được định nghĩa hoặc thay đổi các thuộc tính.
-
props
-
Đối tượng mà các thuộc tính có thể liệt kê (enumerable) của riêng nó sẽ cấu thành các bộ mô tả (descriptor) cho các thuộc tính được định nghĩa hoặc sửa đổi. Các bộ mô tả thuộc tính (property descriptors) có trong các đối tượng bao gồm hai loại chính: các bộ mô tả dữ liệu (data descriptors) và các bộ mô tả truy cập (accessor descriptors) (xem {{jsxref("Object.defineProperty()")}} để biết thêm chi tiết). Các bộ mô tả bao gồm các khóa sau:
-
-
-
configurable
-
true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.
- Defaults to false.
-
enumerable
-
true if and only if this property shows up during enumeration of the properties on the corresponding object.
- Defaults to false.
-
- -
-
value
-
The value associated with the property. Can be any valid JavaScript value (number, object, function, etc).
- Defaults to {{jsxref("undefined")}}.
-
writable
-
true if and only if the value associated with the property may be changed with an {{jsxref("Operators/Assignment_Operators", "assignment operator", "", 1)}}.
- Defaults to false.
-
- -
-
get
-
A function which serves as a getter for the property, or {{jsxref("undefined")}} if there is no getter. The function return will be used as the value of property.
- Defaults to {{jsxref("undefined")}}.
-
set
-
A function which serves as a setter for the property, or {{jsxref("undefined")}} if there is no setter. The function will receive as only argument the new value being assigned to the property.
- Defaults to {{jsxref("undefined")}}.
-
-
-
- -

Giá trị trả về

- -

Đối tượng được truyền khi gọi phương thức.

- -

Mô tả

- -

Object.defineProperties, in essence, defines all properties corresponding to the enumerable own properties of props on the object obj object.

- -

Ví dụ

- -
var obj = {};
-Object.defineProperties(obj, {
-  'property1': {
-    value: true,
-    writable: true
-  },
-  'property2': {
-    value: 'Hello',
-    writable: false
-  }
-  // etc. etc.
-});
-
- -

Polyfill

- -

Assuming a pristine execution environment with all names and properties referring to their initial values, Object.defineProperties is almost completely equivalent (note the comment in isCallable) to the following reimplementation in JavaScript:

- -
function defineProperties(obj, properties) {
-  function convertToDescriptor(desc) {
-    function hasProperty(obj, prop) {
-      return Object.prototype.hasOwnProperty.call(obj, prop);
-    }
-
-    function isCallable(v) {
-      // NB: modify as necessary if other values than functions are callable.
-      return typeof v === 'function';
-    }
-
-    if (typeof desc !== 'object' || desc === null)
-      throw new TypeError('bad desc');
-
-    var d = {};
-
-    if (hasProperty(desc, 'enumerable'))
-      d.enumerable = !!desc.enumerable;
-    if (hasProperty(desc, 'configurable'))
-      d.configurable = !!desc.configurable;
-    if (hasProperty(desc, 'value'))
-      d.value = desc.value;
-    if (hasProperty(desc, 'writable'))
-      d.writable = !!desc.writable;
-    if (hasProperty(desc, 'get')) {
-      var g = desc.get;
-
-      if (!isCallable(g) && typeof g !== 'undefined')
-        throw new TypeError('bad get');
-      d.get = g;
-    }
-    if (hasProperty(desc, 'set')) {
-      var s = desc.set;
-      if (!isCallable(s) && typeof s !== 'undefined')
-        throw new TypeError('bad set');
-      d.set = s;
-    }
-
-    if (('get' in d || 'set' in d) && ('value' in d || 'writable' in d))
-      throw new TypeError('identity-confused descriptor');
-
-    return d;
-  }
-
-  if (typeof obj !== 'object' || obj === null)
-    throw new TypeError('bad obj');
-
-  properties = Object(properties);
-
-  var keys = Object.keys(properties);
-  var descs = [];
-
-  for (var i = 0; i < keys.length; i++)
-    descs.push([keys[i], convertToDescriptor(properties[keys[i]])]);
-
-  for (var i = 0; i < descs.length; i++)
-    Object.defineProperty(obj, descs[i][0], descs[i][1]);
-
-  return obj;
-}
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.7', 'Object.defineProperties')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5
{{SpecName('ES6', '#sec-object.defineproperties', 'Object.defineProperties')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.defineproperties', 'Object.defineProperties')}}{{Spec2('ESDraft')}} 
- -

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

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureFirefox (Gecko)ChromeEdgeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop("2")}}{{CompatChrome("5")}}{{CompatVersionUnknown}}{{CompatIE("9")}}{{CompatOpera("11.60")}}{{CompatSafari("5")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureFirefox Mobile (Gecko)AndroidEdgeIE MobileOpera MobileSafari Mobile
Basic support{{CompatGeckoMobile("2")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatOperaMobile("11.5")}}{{CompatVersionUnknown}}
-
- -

Tham khảo

- - diff --git a/files/vi/web/javascript/reference/global_objects/object/defineproperty/index.html b/files/vi/web/javascript/reference/global_objects/object/defineproperty/index.html deleted file mode 100644 index 87c16604ea..0000000000 --- a/files/vi/web/javascript/reference/global_objects/object/defineproperty/index.html +++ /dev/null @@ -1,483 +0,0 @@ ---- -title: Object.defineProperty() -slug: Web/JavaScript/Reference/Global_Objects/Object/defineProperty -translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperty ---- -
{{JSRef}}
- -

Phương thức Object.defineProperty() định nghĩa ngay một thuộc tính mới trên một đối tượng, hoặc thay đổi một thuộc tính đã có trên một đối tượng, và trả về đối tượng đó.

- -
-

Lưu ý: Bạn có thể gọi phương thức ngay trên  {{jsxref("Object")}} hơn là trên một thể hiện của kiểu Object.

-
- -
{{EmbedInteractiveExample("pages/js/object-defineproperty.html")}}
- - - -

Cú pháp

- -
Object.defineProperty(obj, prop, descriptor)
- -

Các tham số

- -
-
obj
-
Object cần định nghĩa thuộc tính.
-
prop
-
Tên của thuộc tính sẽ định nghĩa hoặc sửa đổi.
-
descriptor
-
Mô tả cho thuộc tính được định nghĩa hoặc sửa đổi.
-
- -

Giá trị trả về

- -

Object đã được truyền vào hàm.

- -

Mô tả

- -

This method allows a precise addition to or modification of a property on an object. Normal property addition through assignment creates properties which show up during property enumeration ({{jsxref("Statements/for...in", "for...in")}} loop or {{jsxref("Object.keys")}} method), whose values may be changed, and which may be {{jsxref("Operators/delete", "deleted", "", 1)}}. This method allows these extra details to be changed from their defaults. By default, values added using Object.defineProperty() are immutable.

- -

Property descriptors present in objects come in two main flavors: data descriptors and accessor descriptors. A data descriptor is a property that has a value, which may or may not be writable. An accessor descriptor is a property described by a getter-setter pair of functions. A descriptor must be one of these two flavors; it cannot be both.

- -

Both data and accessor descriptors are objects. They share the following optional keys:

- -
-
configurable
-
true if and only if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object.
- Defaults to false.
-
enumerable
-
true if and only if this property shows up during enumeration of the properties on the corresponding object.
- Defaults to false.
-
- -

A data descriptor also has the following optional keys:

- -
-
value
-
The value associated with the property. Can be any valid JavaScript value (number, object, function, etc).
- Defaults to {{jsxref("undefined")}}.
-
writable
-
true if and only if the value associated with the property may be changed with an {{jsxref("Operators/Assignment_Operators", "assignment operator", "", 1)}}.
- Defaults to false.
-
- -

An accessor descriptor also has the following optional keys:

- -
-
get
-
A function which serves as a getter for the property, or {{jsxref("undefined")}} if there is no getter. When the property is accessed, this function is called without arguments and with this set to the object through which the property is accessed (this may not be the object on which the property is defined due to inheritance). The return value will be used as the value of the property.
- Defaults to {{jsxref("undefined")}}.
-
set
-
A function which serves as a setter for the property, or {{jsxref("undefined")}} if there is no setter. When the property is assigned to, this function is called with one argument (the value being assigned to the property) and with this set to the object through which the property is assigned.
- Defaults to {{jsxref("undefined")}}.
-
- -

If a descriptor has neither of value, writable, get and set keys, it is treated as a data descriptor. If a descriptor has both value or writable and get or set keys, an exception is thrown.

- -

Bear in mind that these attributes are not necessarily the descriptor's own properties. Inherited properties will be considered as well. In order to ensure these defaults are preserved, you might freeze the {{jsxref("Object.prototype")}} upfront, specify all options explicitly, or point to {{jsxref("null")}} with {{jsxref("Object.create", "Object.create(null)")}}.

- -
// using __proto__
-var obj = {};
-var descriptor = Object.create(null); // no inherited properties
-// not enumerable, not configurable, not writable as defaults
-descriptor.value = 'static';
-Object.defineProperty(obj, 'key', descriptor);
-
-// being explicit
-Object.defineProperty(obj, 'key', {
-  enumerable: false,
-  configurable: false,
-  writable: false,
-  value: 'static'
-});
-
-// recycling same object
-function withValue(value) {
-  var d = withValue.d || (
-    withValue.d = {
-      enumerable: false,
-      writable: false,
-      configurable: false,
-      value: null
-    }
-  );
-  d.value = value;
-  return d;
-}
-// ... and ...
-Object.defineProperty(obj, 'key', withValue('static'));
-
-// if freeze is available, prevents adding or
-// removing the object prototype properties
-// (value, get, set, enumerable, writable, configurable)
-(Object.freeze || Object)(Object.prototype);
-
- -

Ví dụ

- -

If you want to see how to use the Object.defineProperty method with a binary-flags-like syntax, see additional examples.

- -

Creating a property

- -

When the property specified doesn't exist in the object, Object.defineProperty() creates a new property as described. Fields may be omitted from the descriptor, and default values for those fields are inputted.

- -
var o = {}; // Creates a new object
-
-// Example of an object property added
-// with defineProperty with a data property descriptor
-Object.defineProperty(o, 'a', {
-  value: 37,
-  writable: true,
-  enumerable: true,
-  configurable: true
-});
-// 'a' property exists in the o object and its value is 37
-
-// Example of an object property added
-// with defineProperty with an accessor property descriptor
-var bValue = 38;
-Object.defineProperty(o, 'b', {
-  // Using shorthand method names (ES2015 feature).
-  // This is equivalent to:
-  // get: function() { return bValue; },
-  // set: function(newValue) { bValue = newValue; },
-  get() { return bValue; },
-  set(newValue) { bValue = newValue; },
-  enumerable: true,
-  configurable: true
-});
-o.b; // 38
-// 'b' property exists in the o object and its value is 38
-// The value of o.b is now always identical to bValue,
-// unless o.b is redefined
-
-// You cannot try to mix both:
-Object.defineProperty(o, 'conflict', {
-  value: 0x9f91102,
-  get() { return 0xdeadbeef; }
-});
-// throws a TypeError: value appears
-// only in data descriptors,
-// get appears only in accessor descriptors
-
- -

Modifying a property

- -

When the property already exists, Object.defineProperty() attempts to modify the property according to the values in the descriptor and the object's current configuration. If the old descriptor had its configurable attribute set to false the property is said to be “non-configurable”. It is not possible to change any attribute of a non-configurable accessor property. For data properties, it is possible to modify the value if the property is writable, and it is possible to change writable attribute from true to false. It is not possible to switch between data and accessor property types when the property is non-configurable.

- -

A {{jsxref("TypeError")}} is thrown when attempts are made to change non-configurable property attributes (except value and writable, if permitted) unless the current and new values are the same.

- -

Writable attribute

- -

When the writable property attribute is set to false, the property is said to be “non-writable”. It cannot be reassigned.

- -
var o = {}; // Creates a new object
-
-Object.defineProperty(o, 'a', {
-  value: 37,
-  writable: false
-});
-
-console.log(o.a); // logs 37
-o.a = 25; // No error thrown
-// (it would throw in strict mode,
-// even if the value had been the same)
-console.log(o.a); // logs 37. The assignment didn't work.
-
-// strict mode
-(function() {
-  'use strict';
-  var o = {};
-  Object.defineProperty(o, 'b', {
-    value: 2,
-    writable: false
-  });
-  o.b = 3; // throws TypeError: "b" is read-only
-  return o.b; // returns 2 without the line above
-}());
-
- -

As seen in the example, trying to write into the non-writable property doesn't change it but doesn't throw an error either.

- -

Enumerable attribute

- -

The enumerable property attribute defines whether the property shows up in a {{jsxref("Statements/for...in", "for...in")}} loop and {{jsxref("Object.keys()")}} or not.

- -
var o = {};
-Object.defineProperty(o, 'a', {
-  value: 1,
-  enumerable: true
-});
-Object.defineProperty(o, 'b', {
-  value: 2,
-  enumerable: false
-});
-Object.defineProperty(o, 'c', {
-  value: 3
-}); // enumerable defaults to false
-o.d = 4; // enumerable defaults to true
-         // when creating a property by setting it
-
-for (var i in o) {
-  console.log(i);
-}
-// logs 'a' and 'd' (in undefined order)
-
-Object.keys(o); // ['a', 'd']
-
-o.propertyIsEnumerable('a'); // true
-o.propertyIsEnumerable('b'); // false
-o.propertyIsEnumerable('c'); // false
-
- -

Configurable attribute

- -

The configurable attribute controls at the same time whether the property can be deleted from the object and whether its attributes (other than value and writable) can be changed.

- -
var o = {};
-Object.defineProperty(o, 'a', {
-  get() { return 1; },
-  configurable: false
-});
-
-Object.defineProperty(o, 'a', {
-  configurable: true
-}); // throws a TypeError
-Object.defineProperty(o, 'a', {
-  enumerable: true
-}); // throws a TypeError
-Object.defineProperty(o, 'a', {
-  set() {}
-}); // throws a TypeError (set was undefined previously)
-Object.defineProperty(o, 'a', {
-  get() { return 1; }
-}); // throws a TypeError
-// (even though the new get does exactly the same thing)
-Object.defineProperty(o, 'a', {
-  value: 12
-}); // throws a TypeError
-
-console.log(o.a); // logs 1
-delete o.a; // Nothing happens
-console.log(o.a); // logs 1
-
- -

If the configurable attribute of o.a had been true, none of the errors would be thrown and the property would be deleted at the end.

- -

Adding properties and default values

- -

It is important to consider the way default values of attributes are applied. There is often a difference between simply using dot notation to assign a value and using Object.defineProperty(), as shown in the example below.

- -
var o = {};
-
-o.a = 1;
-// is equivalent to:
-Object.defineProperty(o, 'a', {
-  value: 1,
-  writable: true,
-  configurable: true,
-  enumerable: true
-});
-
-// On the other hand,
-Object.defineProperty(o, 'a', { value: 1 });
-// is equivalent to:
-Object.defineProperty(o, 'a', {
-  value: 1,
-  writable: false,
-  configurable: false,
-  enumerable: false
-});
-
- -

Custom Setters and Getters

- -

The example below shows how to implement a self-archiving object. When temperature property is set, the archive array gets a log entry.

- -
function Archiver() {
-  var temperature = null;
-  var archive = [];
-
-  Object.defineProperty(this, 'temperature', {
-    get() {
-      console.log('get!');
-      return temperature;
-    },
-    set(value) {
-      temperature = value;
-      archive.push({ val: temperature });
-    }
-  });
-
-  this.getArchive = function() { return archive; };
-}
-
-var arc = new Archiver();
-arc.temperature; // 'get!'
-arc.temperature = 11;
-arc.temperature = 13;
-arc.getArchive(); // [{ val: 11 }, { val: 13 }]
-
- -

In this example, a getter always returns the same value.

- -
var pattern = {
-    get() {
-        return 'I always return this string, ' +
-               'whatever you have assigned';
-    },
-    set() {
-        this.myname = 'this is my name string';
-    }
-};
-
-function TestDefineSetAndGet() {
-    Object.defineProperty(this, 'myproperty', pattern);
-}
-
-var instance = new TestDefineSetAndGet();
-instance.myproperty = 'test';
-console.log(instance.myproperty);
-// I always return this string, whatever you have assigned
-
-console.log(instance.myname); // this is my name string
-
- -

Inheritance of properties

- -

If an accessor property is inherited, its get and set methods will be called when the property is accessed and modified on descendant objects. If these methods use a variable to store the value, this value will be shared by all objects.

- -
function myclass() {
-}
-
-var value;
-Object.defineProperty(myclass.prototype, "x", {
-  get() {
-    return value;
-  },
-  set(x) {
-    value = x;
-  }
-});
-
-var a = new myclass();
-var b = new myclass();
-a.x = 1;
-console.log(b.x); // 1
-
- -

This can be fixed by storing the value in another property. In get and set methods, this points to the object which is used to access or modify the property.

- -
function myclass() {
-}
-
-Object.defineProperty(myclass.prototype, "x", {
-  get() {
-    return this.stored_x;
-  },
-  set(x) {
-    this.stored_x = x;
-  }
-});
-
-var a = new myclass();
-var b = new myclass();
-a.x = 1;
-console.log(b.x); // undefined
-
- -

Unlike accessor properties, value properties are always set on the object itself, not on a prototype. However, if a non-writable value property is inherited, it still prevents from modifying the property on the object.

- -
function myclass() {
-}
-
-myclass.prototype.x = 1;
-Object.defineProperty(myclass.prototype, "y", {
-  writable: false,
-  value: 1
-});
-
-var a = new myclass();
-a.x = 2;
-console.log(a.x); // 2
-console.log(myclass.prototype.x); // 1
-a.y = 2; // Ignored, throws in strict mode
-console.log(a.y); // 1
-console.log(myclass.prototype.y); // 1
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES5.1', '#sec-15.2.3.6', 'Object.defineProperty')}}{{Spec2('ES5.1')}}Initial definition. Implemented in JavaScript 1.8.5.
{{SpecName('ES6', '#sec-object.defineproperty', 'Object.defineProperty')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.defineproperty', 'Object.defineProperty')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.Object.defineProperty")}}

-
- -

Compatibility notes

- -

Redefining the length property of an Array object

- -

It is possible to redefine the {{jsxref("Array.length", "length")}} property of arrays, subject to the usual redefinition restrictions. (The {{jsxref("Array.length", "length")}} property is initially non-configurable, non-enumerable, and writable. Thus on an unaltered array, it's possible to change the {{jsxref("Array.length", "length")}} property's value or to make it non-writable. It is not allowed to change its enumerability or configurability, or if it is non-writable to change its value or writability.) However, not all browsers permit this redefinition.

- -

Firefox 4 through 22 will throw a {{jsxref("TypeError")}} on any attempt whatsoever (whether permitted or not) to redefine the {{jsxref("Array.length", "length")}} property of an array.

- -

Versions of Chrome which implement Object.defineProperty() in some circumstances ignore a length value different from the array's current {{jsxref("Array.length", "length")}} property. In some circumstances changing writability seems to silently not work (and not throw an exception). Also, relatedly, some array-mutating methods like {{jsxref("Array.prototype.push")}} don't respect a non-writable length.

- -

Versions of Safari which implement Object.defineProperty() ignore a length value different from the array's current {{jsxref("Array.length", "length")}} property, and attempts to change writability execute without error but do not actually change the property's writability.

- -

Only Internet Explorer 9 and later, and Firefox 23 and later, appear to fully and correctly implement redefinition of the {{jsxref("Array.length", "length")}} property of arrays. For now, don't rely on redefining the {{jsxref("Array.length", "length")}} property of an array to either work, or to work in a particular manner. And even when you can rely on it, there's really no good reason to do so.

- -

Internet Explorer 8 specific notes

- -

Internet Explorer 8 implemented a Object.defineProperty() method that could only be used on DOM objects. A few things need to be noted:

- - - -

See also

- - diff --git a/files/vi/web/javascript/reference/global_objects/object/getownpropertynames/index.html b/files/vi/web/javascript/reference/global_objects/object/getownpropertynames/index.html deleted file mode 100644 index d1e533fceb..0000000000 --- a/files/vi/web/javascript/reference/global_objects/object/getownpropertynames/index.html +++ /dev/null @@ -1,156 +0,0 @@ ---- -title: Object.getOwnPropertyNames() -slug: Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames -translation_of: Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyNames ---- -
{{JSRef}}
- -

The Object.getOwnPropertyNames() phuong thuc nay tra ve mang (including non-enumerable properties except for those which use Symbol) found directly in a given object.

- -
{{EmbedInteractiveExample("pages/js/object-getownpropertynames.html")}}
- -

Syntax

- -
Object.getOwnPropertyNames(obj)
- -

Parameters

- -
-
obj
-
The object whose enumerable and non-enumerable properties are to be returned.
-
- -

Return value

- -

An array of strings that corresponds to the properties found directly in the given object.

- -

Description

- -

Object.getOwnPropertyNames() returns an array whose elements are strings corresponding to the enumerable and non-enumerable properties found directly in a given object obj. The ordering of the enumerable properties in the array is consistent with the ordering exposed by a {{jsxref("Statements/for...in", "for...in")}} loop (or by {{jsxref("Object.keys()")}}) over the properties of the object. The ordering of the non-enumerable properties in the array and the ordering among the enumerable properties is not defined.

- -

Examples

- -

Using Object.getOwnPropertyNames()

- -
var arr = ['a', 'b', 'c'];
-console.log(Object.getOwnPropertyNames(arr).sort());
-// logs ["0", "1", "2", "length"]
-
-// Array-like object
-var obj = { 0: 'a', 1: 'b', 2: 'c' };
-console.log(Object.getOwnPropertyNames(obj).sort());
-// logs ["0", "1", "2"]
-
-// Logging property names and values using Array.forEach
-Object.getOwnPropertyNames(obj).forEach(
-  function (val, idx, array) {
-    console.log(val + ' -> ' + obj[val]);
-  }
-);
-// logs
-// 0 -> a
-// 1 -> b
-// 2 -> c
-
-// non-enumerable property
-var my_obj = Object.create({}, {
-  getFoo: {
-    value: function() { return this.foo; },
-    enumerable: false
-  }
-});
-my_obj.foo = 1;
-
-console.log(Object.getOwnPropertyNames(my_obj).sort());
-// logs ["foo", "getFoo"]
-
- -

If you want only the enumerable properties, see {{jsxref("Object.keys()")}} or use a {{jsxref("Statements/for...in", "for...in")}} loop (note that this will also return enumerable properties found along the prototype chain for the object unless the latter is filtered with {{jsxref("Object.prototype.hasOwnProperty()", "hasOwnProperty()")}}).

- -

Items on the prototype chain are not listed:

- -
function ParentClass() {}
-ParentClass.prototype.inheritedMethod = function() {};
-
-function ChildClass() {
-  this.prop = 5;
-  this.method = function() {};
-}
-ChildClass.prototype = new ParentClass;
-ChildClass.prototype.prototypeMethod = function() {};
-
-console.log(
-  Object.getOwnPropertyNames(
-    new ChildClass() // ["prop", "method"]
-  )
-);
-
- -

Get non-enumerable properties only

- -

This uses the {{jsxref("Array.prototype.filter()")}} function to remove the enumerable keys (obtained with {{jsxref("Object.keys()")}}) from a list of all keys (obtained with Object.getOwnPropertyNames()) thus giving only the non-enumerable keys as output.

- -
var target = myObject;
-var enum_and_nonenum = Object.getOwnPropertyNames(target);
-var enum_only = Object.keys(target);
-var nonenum_only = enum_and_nonenum.filter(function(key) {
-  var indexInEnum = enum_only.indexOf(key);
-  if (indexInEnum == -1) {
-    // Not found in enum_only keys,
-    // meaning that the key is non-enumerable,
-    // so return true so we keep this in the filter
-    return true;
-  } else {
-    return false;
-  }
-});
-
-console.log(nonenum_only);
-
- -

Notes

- -

In ES5, if the argument to this method is not an object (a primitive), then it will cause a {{jsxref("TypeError")}}. In ES2015, a non-object argument will be coerced to an object.

- -
Object.getOwnPropertyNames('foo');
-// TypeError: "foo" is not an object (ES5 code)
-
-Object.getOwnPropertyNames('foo');
-// ["0", "1", "2", "length"]  (ES2015 code)
-
- -

Specifications

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-object.getownpropertynames', 'Object.getOwnPropertyNames')}}
- -

Browser compatibility

- - - -

{{Compat("javascript.builtins.Object.getOwnPropertyNames")}}

- -

Firefox-specific notes

- -

Prior to Firefox 28, Object.getOwnPropertyNames did not see unresolved properties of {{jsxref("Error")}} objects. This has been fixed in later versions (bug 724768).

- -

See also

- - diff --git a/files/vi/web/javascript/reference/global_objects/object/index.html b/files/vi/web/javascript/reference/global_objects/object/index.html deleted file mode 100644 index 06fd8ef967..0000000000 --- a/files/vi/web/javascript/reference/global_objects/object/index.html +++ /dev/null @@ -1,213 +0,0 @@ ---- -title: Object -slug: Web/JavaScript/Reference/Global_Objects/Object -tags: - - Constructor - - JavaScript - - NeedsTranslation - - Object - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/Object ---- -
{{JSRef}}
- -

The Object constructor creates an object wrapper.

- -

Syntax

- -
// Object initialiser or literal
-{ [ nameValuePair1[, nameValuePair2[, ...nameValuePairN] ] ] }
-
-// Called as a constructor
-new Object([value])
- -

Parameters

- -
-
nameValuePair1, nameValuePair2, ... nameValuePairN
-
Pairs of names (strings) and values (any value) where the name is separated from the value by a colon.
-
value
-
Any value.
-
- -

Description

- -

The Object constructor creates an object wrapper for the given value. If the value is {{jsxref("null")}} or {{jsxref("undefined")}}, it will create and return an empty object, otherwise, it will return an object of a Type that corresponds to the given value. If the value is an object already, it will return the value.

- -

When called in a non-constructor context, Object behaves identically to new Object().

- -

See also the object initializer / literal syntax.

- -

Properties of the Object constructor

- -
-
Object.length
-
Has a value of 1.
-
{{jsxref("Object.prototype")}}
-
Allows the addition of properties to all objects of type Object.
-
- -

Methods of the Object constructor

- -
-
{{jsxref("Object.assign()")}} {{experimental_inline}}
-
Creates a new object by copying the values of all enumerable own properties from one or more source objects to a target object.
-
{{jsxref("Object.create()")}}
-
Creates a new object with the specified prototype object and properties.
-
{{jsxref("Object.defineProperty()")}}
-
Adds the named property described by a given descriptor to an object.
-
{{jsxref("Object.defineProperties()")}}
-
Adds the named properties described by the given descriptors to an object.
-
{{jsxref("Object.freeze()")}}
-
Freezes an object: other code can't delete or change any properties.
-
{{jsxref("Object.getOwnPropertyDescriptor()")}}
-
Returns a property descriptor for a named property on an object.
-
{{jsxref("Object.getOwnPropertyNames()")}}
-
Returns an array containing the names of all of the given object's own enumerable and non-enumerable properties.
-
{{jsxref("Object.getOwnPropertySymbols()")}} {{experimental_inline}}
-
Returns an array of all symbol properties found directly upon a given object.
-
{{jsxref("Object.getPrototypeOf()")}}
-
Returns the prototype of the specified object.
-
{{jsxref("Object.is()")}} {{experimental_inline}}
-
Compares if two values are distinguishable (ie. the same)
-
{{jsxref("Object.isExtensible()")}}
-
Determines if extending of an object is allowed.
-
{{jsxref("Object.isFrozen()")}}
-
Determines if an object was frozen.
-
{{jsxref("Object.isSealed()")}}
-
Determines if an object is sealed.
-
{{jsxref("Object.keys()")}}
-
Returns an array containing the names of all of the given object's own enumerable properties.
-
{{jsxref("Object.observe()")}} {{experimental_inline}}
-
Asynchronously observes changes to an object.
-
{{jsxref("Object.preventExtensions()")}}
-
Prevents any extensions of an object.
-
{{jsxref("Object.seal()")}}
-
Prevents other code from deleting properties of an object.
-
{{jsxref("Object.setPrototypeOf()")}} {{experimental_inline}}
-
Sets the prototype (i.e., the internal [[Prototype]] property)
-
- -

Object instances and Object prototype object

- -

All objects in JavaScript are descended from Object; all objects inherit methods and properties from {{jsxref("Object.prototype")}}, although they may be overridden. For example, other constructors' prototypes override the constructor property and provide their own toString() methods. Changes to the Object prototype object are propagated to all objects unless the properties and methods subject to those changes are overridden further along the prototype chain.

- -

Properties

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

Methods

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

Examples

- -

Using Object given undefined and null types

- -

The following examples store an empty Object object in o:

- -
var o = new Object();
-
- -
var o = new Object(undefined);
-
- -
var o = new Object(null);
-
- -

Using Object to create Boolean objects

- -

The following examples store {{jsxref("Boolean")}} objects in o:

- -
// equivalent to o = new Boolean(true);
-var o = new Object(true);
-
- -
// equivalent to o = new Boolean(false);
-var o = new Object(Boolean());
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2', 'Object')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object-objects', 'Object')}}{{Spec2('ES6')}} 
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

See also

- - diff --git a/files/vi/web/javascript/reference/global_objects/object/tostring/index.html b/files/vi/web/javascript/reference/global_objects/object/tostring/index.html deleted file mode 100644 index 78a46f1272..0000000000 --- a/files/vi/web/javascript/reference/global_objects/object/tostring/index.html +++ /dev/null @@ -1,128 +0,0 @@ ---- -title: Object.prototype.toString() -slug: Web/JavaScript/Reference/Global_Objects/Object/toString -translation_of: Web/JavaScript/Reference/Global_Objects/Object/toString ---- -
{{JSRef}}
- -

Phương thức toString() trả về một chuỗi đại diện cho object.

- -

Cú pháp

- -
obj.toString()
- -

Giá trị trả về

- -

Một chuỗi đại diện cho object.

- -

Miêu tả

- -

Mỗi object có 1 phương thức toString(). Phương thức này được tự động gọi khi object được biểu diễn dưới dạng text hoặc trong bối cảnh mà một chuỗi được mong đợi để trả về. Mặc định, phương thức toString() được kế thừa cho tất cả object khi tất cả object được kế thừa từ Object. Nếu phương thức này không bị ghi đè bởi một object đã được tuỳ chỉnh, phương thức này trả về "[object type]", trong đó type là kiểu của object. Phần code theo sau mô tả điều này:

- -
var o = new Object();
-o.toString(); // returns [object Object]
-
- -
-

Note: Kể từ JavaScript 1.8.5, toString() khi được gọi trong {{jsxref("null")}} sẽ trả về [object Null], và {{jsxref("undefined")}} sẽ trả về [object Undefined], như đã được định nghĩa trong 5th Edition of ECMAScript and a subsequent Errata. Tham khảo {{anch("Using_toString()_to_detect_object_class", "Using_toString()_to_detect_object_class")}}.

-
- -

Ví dụ

- -

Ghi đè phương thức mặc định toString

- -

Bạn có thể tạo một hàm để thay thể phương thức mặc định toString(). Phương thức mặc định toString() không có tham số truyền vào và sẽ trả về một chuỗi. Phương thức toString() bạn tự tạo có thể trả về bất kì giá trị gì bạn muốn, nhưng sẽ tốt hơn nếu nó mang thông tin về object.

- -

Phần code sau đây định nghĩa kiểu Dog object và tạo ra theDog, một object của kiểu Dog:

- -
function Dog(name, breed, color, sex) {
-  this.name = name;
-  this.breed = breed;
-  this.color = color;
-  this.sex = sex;
-}
-
-theDog = new Dog('Gabby', 'Lab', 'chocolate', 'female');
-
- -

Nếu bạn gọi phương thức toString() trên object tuỳ chỉnh này, nó sẽ trả về giá trị mặc định được kế thừa từ {{jsxref("Object")}}:

- -
theDog.toString(); // returns [object Object]
-
- -

Phần code sau đây tạo ra và gán dogToString() để ghi đè lên phương thức mặc định toString(). Hàm này sẽ tạo một chuỗi chứa tên, giống, màu và giới tính của object, theo dạng "property = value;".

- -
Dog.prototype.toString = function dogToString() {
-  var ret = 'Dog ' + this.name + ' is a ' + this.sex + ' ' + this.color + ' ' + this.breed;
-  return ret;
-}
-
- -

Với phần code ở phía trên, mỗi khi theDog được sử dụng để trả về một chuỗi, JavaScript sẽ tự động gọi hàm dogToString(), trả về kết quả sau:

- -
"Dog Gabby is a female chocolate Lab"
-
- -

Sử dụng toString() để xác định lớp đối tượng

- -

toString() có thể được sử dụng với tất cả object và cho phép bạn xác định lớp của object đó. Để sử dụng Object.prototype.toString() với mọi đối tượng, bạn cần gọi {{jsxref("Function.prototype.call()")}} or {{jsxref("Function.prototype.apply()")}} trên object đó, truyền vào object mà bạn muốn vào tham số đầu tiên hay còn được gọi là thisArg.

- -
var toString = Object.prototype.toString;
-
-toString.call(new Date);    // [object Date]
-toString.call(new String);  // [object String]
-toString.call(Math);        // [object Math]
-
-// Since JavaScript 1.8.5
-toString.call(undefined);   // [object Undefined]
-toString.call(null);        // [object Null]
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.2.4.2', 'Object.prototype.toString')}}{{Spec2('ES5.1')}}Call on {{jsxref("null")}} returns [object Null], and {{jsxref("undefined")}} returns [object Undefined]
{{SpecName('ES6', '#sec-object.prototype.tostring', 'Object.prototype.toString')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-object.prototype.tostring', 'Object.prototype.toString')}}{{Spec2('ESDraft')}}
- -

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

- -
- - -

{{Compat("javascript.builtins.Object.toString")}}

-
- -

Tham khảo thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/object/valueof/index.html b/files/vi/web/javascript/reference/global_objects/object/valueof/index.html deleted file mode 100644 index 44a440e1f6..0000000000 --- a/files/vi/web/javascript/reference/global_objects/object/valueof/index.html +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: Object.prototype.valueOf() -slug: Web/JavaScript/Reference/Global_Objects/Object/valueOf -translation_of: Web/JavaScript/Reference/Global_Objects/Object/valueOf ---- -
{{JSRef}}
- -

Phương thức valueOf() trả về giá trị nguyên thuỷ(primitive value) của object đang được nói tới.

- -

Cú pháp

- -
object.valueOf()
- -

Giá trị trả về

- -

Giá trị nguyên thuỷ(primitive value) của object đang được nói tới.

- -

Miêu tả

- -

JavaScript gọi phương thức valueOf để chuyển đổi một object sang một giá trị nguyên thuỷ. Bạn hiếp khi cần gọi phương thức valueOf bởi chính bạn; JavaScript tự động gọi nó khi gặp phải một object ở chỗ mà một giá trị nguyên thuỷ cần được trả về.

- -

Mặc định, phương thức valueOf được kế thừa cho mọi object khi mà mọi object đó được kế thừa từ {{jsxref("Object")}}. Mọi core-object được tạo sẵn để ghi đè phương thức này để trả về giá trị phù hợp. Nếu một object ko có giá trị nguyên thuỷ, valueOf sẽ trả về chính object đó.

- -

Bạn có thể sử dụng valueOf trong code của bạn để chuyển đổi một object được tạo sẵn thành một giá trị nguyên thuỷ. Khi bạn tạo một object tuỳ chỉnh, bạn có thể ghi đè Object.prototype.valueOf() để gọi phương thức tuỳ chỉnh thay vì phương thức mặc định {{jsxref("Object")}}.

- -

Ghi đè valueOf cho object tuỳ chỉnh

- -

Bạn có thể tạo một hàm để được gọi thay thể cho phương thức valueOf. Hàm của bạn phải không nhận tham số nào cả.

- -

Giả sử bạn có một object loại MyNumberType và bạn muốn tạo một phương thức valueOf cho nó. Phần code sau đây gán một hàm định nghĩa bới người dùng cho phương thức valueOf của object:

- -
MyNumberType.prototype.valueOf = function() { return customPrimitiveValue; };
- -

 

- -

Với phần code phía trên, mỗi khi một object loại MyNumberType được sử dụng trong bối cảnh mà nó cần được biểu diễn bởi một giá trị nguyên thuỷ, JavaScript sẽ tự động gọi hàm đã được viết trên đây.

- -

Một phương thức valueOf của object thường được gọi bởi JavaScript, nhưng bạn có thể tự gọi nó bằng cách sau:

- -
myNumberType.valueOf()
- -
-

Note: Objects in string contexts convert via the {{jsxref("Object.toString", "toString()")}} method, which is different from {{jsxref("String")}} objects converting to string primitives using valueOf. All objects have a string conversion, if only "[object type]". But many objects do not convert to number, boolean, or function.

-
- -

Ví dụ

- -

Sử dụng valueOf

- -
function MyNumberType(n) {
-    this.number = n;
-}
-
-MyNumberType.prototype.valueOf = function() {
-    return this.number;
-};
-
-var myObj = new MyNumberType(4);
-myObj + 3; // 7
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.2.4.4', 'Object.prototype.valueOf')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-object.prototype.valueof', 'Object.prototype.valueOf')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-object.prototype.valueof', 'Object.prototype.valueOf')}}{{Spec2('ESDraft')}} 
- -

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

- -
- - -

{{Compat("javascript.builtins.Object.valueOf")}}

-
- -

See also

- - diff --git a/files/vi/web/javascript/reference/global_objects/promise/all/index.html b/files/vi/web/javascript/reference/global_objects/promise/all/index.html deleted file mode 100644 index 403b8b5161..0000000000 --- a/files/vi/web/javascript/reference/global_objects/promise/all/index.html +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: Promise.all() -slug: Web/JavaScript/Reference/Global_Objects/Promise/all -translation_of: Web/JavaScript/Reference/Global_Objects/Promise/all ---- -
{{JSRef}}
- -

Phương thức Promise.all(iterable) trả ra một Promise mới và promise mới này chỉ được kết thúc khi tất cả các promise trong iterable kết thúc hoặc có một promise nào đó xử lý thất bại. Kết quả của promise mới này là một mảng chứa kết quả của tất cả các promise theo đúng thứ tự hoặc kết quả lỗi của promise gây lỗi.

- -

Cú pháp

- -
Promise.all(iterable);
- -

Tham số

- -
-
iterable
-
Một đối tượng có thể duyệt lặp. Ví dụ như một mảng {{jsxref("Array")}}. Để hiểu thêm về đối tượng có thể duyệt lặp, bạn có thể xem tại đây iterable.
-
- -

Đầu ra

- -

Kết quả trả ra là một {{jsxref("Promise")}}. Promise này chỉ được kết thúc khi mà tất cả các promise trong interable truyền vào được kết thúc hoặc một promise nào đó thất bại.

- -

Mô tả

- -

Promise.all sẽ lưu kết quả trả ra của tất cả các promise bằng một mảng theo đúng thứ tự của các promise đầu vào. Bạn lưu ý là thứ tự của các promise đầu vào chứ không phải là thứ tự kết thúc cả các promise. Ngoài ra, với các phần tử đầu vào không phải là một Promise, thì nó sẽ được coi là một giá trị trả ra và được trả với phương thức {{jsxref("Promise.resolve")}}. Tức là nó được đóng gói với 1 promise mới chứa kết quả là chính nó. 

- -

Nếu một promise nào đó bị lỗi, thì Promise.all sẽ bị kết thúc với mã lỗi của promise lỗi đó ngay lập tức. Trong trường hợp này, tất cả các promise khác dù đã kết thúc hay chưa thì đều không được quan tâm nữa.

- -

Ví dụ

- -

Sử dụng Promise.all

- -

Promise.all đợi tất cả các promise kết thúc, hoặc một promise nào đó thât bại.

- -
var p1 = Promise.resolve(3);
-var p2 = 1337;
-var p3 = new Promise((resolve, reject) => {
-  setTimeout(resolve, 100, "foo");
-});
-
-Promise.all([p1, p2, p3]).then(values => {
-  console.log(values); // [3, 1337, "foo"]
-});
- -

Promise.all kết thúc ngay khi có lỗi

- -

Promise.all sẽ bị kết thúc lỗi ngay khi có một promise nào đó bị lỗi.

- -
var p1 = new Promise((resolve, reject) => {
-  setTimeout(resolve, 1000, "one");
-});
-var p2 = new Promise((resolve, reject) => {
-  setTimeout(resolve, 2000, "two");
-});
-var p3 = new Promise((resolve, reject) => {
-  setTimeout(resolve, 3000, "three");
-});
-var p4 = new Promise((resolve, reject) => {
-  setTimeout(resolve, 4000, "four");
-});
-var p5 = new Promise((resolve, reject) => {
-  reject("reject");
-});
-
-Promise.all([p1, p2, p3, p4, p5]).then(values => {
-  console.log(values);
-}, reason => {
-  console.log(reason)
-});
-
-//From console:
-//"reject"
-
-// Evenly, it's possible to use .catch
-Promise.all([p1, p2, p3, p4, p5]).then(values => {
-  console.log(values);
-}).catch(reason => {
-  console.log(reason)
-});
-
-//From console:
-//"reject"
-
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES6', '#sec-promise.all', 'Promise.all')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.all', 'Promise.all')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt tương thích

- - - -

{{Compat}}

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/promise/catch/index.html b/files/vi/web/javascript/reference/global_objects/promise/catch/index.html deleted file mode 100644 index 0564b81afd..0000000000 --- a/files/vi/web/javascript/reference/global_objects/promise/catch/index.html +++ /dev/null @@ -1,136 +0,0 @@ ---- -title: Promise.prototype.catch() -slug: Web/JavaScript/Reference/Global_Objects/Promise/catch -translation_of: Web/JavaScript/Reference/Global_Objects/Promise/catch ---- -
{{JSRef}}
- -

Phương thức catch() trả ra một Promise để xử lý trường hợp xử lý của ta thất bại. Nó cũng giống như {{jsxref("Promise.then", "Promise.prototype.then(undefined, onRejected)")}} nhưng chỉ được gọi khi thao tác của ta thất bại.

- -

Cú pháp

- -
p.catch(onRejected);
-
-p.catch(function(reason) {
-   // rejection
-});
-
- -

Tham số

- -
-
onRejected
-
Một hàm {{jsxref("Function")}} được gọi khi mà Promise của ta thất bại. Hàm này có một tham số đầu vào là: -
-
reason
-
Lý do lỗi.
-
-
-
- -

Trả ra

- -

Một {{jsxref("Promise")}} mới.

- -

Mô tả

- -

Phương thước catch rất hữu ích cho việc xử lý các lỗi xảy ra trong 1 Promise hoặc một chuỗi Promise có quan hệ thứ tự với nhau (đợi nhau).

- -

Ví dụ

- -

Sử dụng phương thức catch

- -
var p1 = new Promise(function(resolve, reject) {
-  resolve('Success');
-});
-
-p1.then(function(value) {
-  console.log(value); // "Success!"
-  throw 'oh, no!';
-}).catch(function(e) {
-  console.log(e); // "oh, no!"
-}).then(function(){
-  console.log('after a catch the chain is restored');
-}, function () {
-  console.log('Not fired due to the catch');
-});
-
-// The following behaves the same as above
-p1.then(function(value) {
-  console.log(value); // "Success!"
-  return Promise.reject('oh, no!');
-}).catch(function(e) {
-  console.log(e); // "oh, no!"
-}).then(function(){
-  console.log('after a catch the chain is restored');
-}, function () {
-  console.log('Not fired due to the catch');
-});
-
- -

Lấy mã lỗi khi ném lỗi

- -
// Throwing an error will call the catch method most of the time
-var p1 = new Promise(function(resolve, reject) {
-  throw 'Uh-oh!';
-});
-
-p1.catch(function(e) {
-  console.log(e); // "Uh-oh!"
-});
-
-// Errors thrown inside asynchronous functions will act like uncaught errors
-var p2 = new Promise(function(resolve, reject) {
-  setTimeout(function() {
-    throw 'Uncaught Exception!';
-  }, 1000);
-});
-
-p2.catch(function(e) {
-  console.log(e); // This is never called
-});
-
-// Errors thrown after resolve is called will be silenced
-var p3 = new Promise(function(resolve, reject) {
-  resolve();
-  throw 'Silenced Exception!';
-});
-
-p3.catch(function(e) {
-   console.log(e); // This is never called
-});
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES6', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise.prototype.catch', 'Promise.prototype.catch')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- - - -

{{Compat}}

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/promise/finally/index.html b/files/vi/web/javascript/reference/global_objects/promise/finally/index.html deleted file mode 100644 index a8796382a2..0000000000 --- a/files/vi/web/javascript/reference/global_objects/promise/finally/index.html +++ /dev/null @@ -1,95 +0,0 @@ ---- -title: Promise.prototype.finally() -slug: Web/JavaScript/Reference/Global_Objects/Promise/finally -translation_of: Web/JavaScript/Reference/Global_Objects/Promise/finally ---- -
{{JSRef}}
- -

Phương thức finally() trả về một {{jsxref("Promise")}}. Một khi promise được thực hiện (settle), dù kết quả là fulfilled hay rejected, thì hàm callback đã chỉ định sẽ được thực thi. Đây là cách để làm cho một đoạn code phải được thực thi sau khi Promise hoàn thành, dù kết quả là fulfilled hay rejected.

- -

Cách này giúp bạn tránh phải viết những dòng code trùng lặp giữa hai phương thức xử lý {{jsxref("Promise.then", "then()")}} và {{jsxref("Promise.catch", "catch()")}}.

- -

Syntax

- -
p.finally(onFinally);
-
-p.finally(function() {
-   // settled (fulfilled or rejected)
-});
-
- -

Parameters

- -
-
onFinally
-
Một {{jsxref("Function")}} được gọi khi Promise được thực hiện
-
- -

Return value

- -

Return a {{jsxref("Promise")}} whose finally handler is set to the specified function, onFinally.

- -

Description

- -

Phương thức finally() hữu ích khi bạn muốn xử lý công việc sau khi promise được thực hiện.

- -

Phương thức finally() cũng tương tự như việc gọi .then(onFinally, onFinally) , tuy nhiên có một số sự khác biệt:

- - - -
-

Note: Một throw (hoặc trả về một promise bị reject) trong callback finally sẽ reject cái promise mới với lý do reject được chỉ định khi gọi throw().

-
- -

Examples

- -
let isLoading = true;
-
-fetch(myRequest).then(function(response) {
-    var contentType = response.headers.get("content-type");
-    if(contentType && contentType.includes("application/json")) {
-      return response.json();
-    }
-    throw new TypeError("Oops, we haven't got JSON!");
-  })
-  .then(function(json) { /* process your JSON further */ })
-  .catch(function(error) { console.log(error); })
-  .finally(function() { isLoading = false; });
-
-
- -

Specifications

- - - - - - - - - - - - - - -
SpecificationStatusComment
TC39 proposalStage 4 
- -

Browser compatibility

- - - -

{{Compat("javascript.builtins.Promise.finally")}}

- -

See also

- - diff --git a/files/vi/web/javascript/reference/global_objects/promise/index.html b/files/vi/web/javascript/reference/global_objects/promise/index.html deleted file mode 100644 index 9b069daf74..0000000000 --- a/files/vi/web/javascript/reference/global_objects/promise/index.html +++ /dev/null @@ -1,317 +0,0 @@ ---- -title: Promise -slug: Web/JavaScript/Reference/Global_Objects/Promise -translation_of: Web/JavaScript/Reference/Global_Objects/Promise ---- -
{{JSRef}}
- -

Promise là một đối tượng đặc biệt dùng cho các xử lý bất đồng bộ. Nó đại diện cho một xử lý bất đồng bộ và chứa kết quả cũng như các lỗi xảy ra từ xử lý bất đồng bộ đó.

- -

Cú pháp

- -
new Promise(executor);
-new Promise(function(resolve, reject) { ... } );
- -

Tham số đầu vào

- -
-
executor
-
Một hàm có 2 tham số đầu vào là 2 hàm phản hồi resolve và reject. Hàm resolve sẽ được gọi khi xử lý thành công, còn reject sẽ được gọi khi xử lý thất bại. 
-
* Chú ý: 2 hàm phản hồi này rất dễ bị nhầm lẫn với phong cách của hàm phản hồi của Node.js. Với Node.js hàm phản hồi lỗi thường là tham số đầu tiên, còn Promise thì ngược lại.
-
Hàm executor sẽ được gọi ngay khi Promise được gọi tới, tức là nó còn được chạy trước cả hàm khởi tạo trả ra kết quả của Promise. Sau khi xử lý kết thúc tùy theo tình huống mà hàm phản hồi resolve hoặc reject sẽ được gọi tới. Trường hợp xử lý thành công thì hàm resolve sẽ được gọi tới để trả ra kết quả. Còn trường hợp thất bại thì hàm reject sẽ được gọi tới để trả ra mã lỗi thực thi.
-
- -

Mô tả

- -

Một Promise có thể như một proxy đại diện cho một giá trị mà ta không cần phải biết ngay khi khởi tạo. Bằng các sử dụng Promise  ta có thể kết hợp với các hàm xử lý khác để sử dụng kết quả sau khi thực thi xử lý bất đồng bộ mà nó đang đại diện. Vì vậy mà ta có thể lập trình bất đồng bộ gần giống với kiểu lập trình đồng bộ - tức là đợi xử lý bất đồng bộ xong mới thực thi các thao tác mà cần sử dụng tới kết quả của xử lý đó. Để có thể làm được việc đó thay vì trả ra kết quả của việc xử lý đồng bộ, Promise  sẽ trả ra một promise khác. Bằng promise mới này ta lại có thể lặp lại việc sử dụng kết quả của thao tác xử lý lúc trước để làm đầu vào cho các thao tác xử lý lúc sau.

- -

Tại mỗi thời điểm Promise sẽ có thể ở một trong các trạng thái sau:

- - - -

Như vậy một Promise khi ở trạng thái pending sẽ được chuyển thành trạng thái fulfilled với kết quả thành công hoặc trạng thái rejected kèm với mã lỗi xảy ra khi xử lý kết thúc. Sau khi xử lý kết thúc, bất kể trạng thái được chuyển thành là thành công hay thất bại thì các hàm xử lý được đính kèm sẽ được gọi thực thi. Để đính kèm một hàm cho Promise, ta có thể sử dụng {{jsxref("Promise.then", "Promise.prototype.then()")}} cho trường hợp thành công và {{jsxref("Promise.catch", "Promise.prototype.catch()")}} cho trường hợp xử lý thất bại.

- -

Hàm đính kèm xử lý {{jsxref("Promise.then", "Promise.prototype.then()")}} và {{jsxref("Promise.catch", "Promise.prototype.catch()")}} sẽ trả ra một promise khác nên thao tác hậu xử lý bằng hàm đính kèm có thể được chuyển tiếp kiểu xử lý chuỗi (chained). Cụ thể hơn ta có thể xem hình dưới đây.

- -

- -

Như hình minh họa hoạt động của Promise trên, ta có thể thấy khi khởi tạo Promise sẽ có trạng thái là pending. Sau khi xử lý kết thúc, tùy theo kết quả xử lý mà trạng thái sẽ là fullfil hoặc reject. Lúc đó các hàm đính kèm sẽ được thực thi thông qua hàm {{jsxref("Promise.then", "Promise.prototype.then()")}} hoặc {{jsxref("Promise.catch", "Promise.prototype.catch()")}}. Chính các hàm này lại trả ra một Promise khác nên ta có thể xử lý một loạt các thao tác phía sau một cách chuyển tiếp.

- -

 

- -
-

Đừng nhầm lẫn với: một số ngôn ngữ khác như Scheme cũng có khái niệm “promises” - nhưng khái niệm này để chỉ thị một thao tác được gọi thực thi sau. Còn, Promises trong JavaScript biểu diễn các thao tác bất đồng bộ mà đã được thực thi (thao tác bất đồng bộ này được gọi ngay khi ta gọi Promise - ngay cả trước khi hàm khởi tạo của Promise được gọi tới) và có thể đính kèm các hàm hậu xử lý sau khi xử lý bất đồng bộ mà nó biểu diễn kết thúc. Nếu bạn muốn dùng các thao tác kiểu thi sau như vậy thì có thể sử dụng hàm mũi tên (arrow function) không có tham số đầu vào, như: f = () => expression để tạo một hàm được gọi sau, và sử dụng f() để thực thi nó.

-
- -
-

Lưu ý: Promise được gọi kết thúc (settled) khi và chỉ khi nó ở trạng thái fulfilled (thành công) hoặc rejected (thất bại). Đôi lúc có thể bạn thấy đâu đó nói rằng Promise được giải quyết xong (resolved) để ám chỉ rằng Promise được kết thúc, lúc đó đừng nhầm lẫn là nó được kết thúc thành công vì nó chỉ đơn giản là nói tới Promise đã được kết thúc mà thôi. Để biết rõ hơn về các thuật ngữ liên quan tới Promise, bạn có thể tham khảo bài viết này: States and fates.

-
- -

Thuộc tính

- -
-
Promise.length
-
Thuộc tính length này luôn có giá trị là 1 (số lượng của tham số khởi tạo).
-
{{jsxref("Promise.prototype")}}
-
Biểu diễn prototype cho hàm khởi tạo Promise.
-
- -

Phương thức

- -
-
{{jsxref("Promise.all", "Promise.all(iterable)")}}
-
Phương thức này được sử dụng khi ta cần đợi một tập các Promise kết thúc. Trả ra một promise đại diện cho tất cả các kết quả thu được từ các promise nằm trong iterable sau khi tất cả các promise này kết thúc xử lý thành công. Hoặc, trả ra một promise đại diện cho lỗi thực thi ngay khi một promise nào đó kết thúc lỗi, khi đó promise được trả ra cũng sẽ ở trạng thái lỗi. Khi tất cả các promise trong iterable kết thúc thành công thì promise trả ra cũng ở trạng thái thành công với kết quả là một mảng chứa tất cả các kết quả của các promise đã thực thi theo đúng thứ tự trong iterable. Còn khi một promise nào đó xảy ra lỗi thì promise được trả ra cũng sẽ ở trạng thái lỗi và chứa mã lỗi của promise đầu tiên gây lỗi đó.
-
{{jsxref("Promise.race", "Promise.race(iterable)")}}
-
Trả ra một promise ngay sau khi một trong các promise trong iterable kết thúc xử lý. Tức là dù kết quả thu được là lỗi hay thành công thì ta cũng sẽ trả ngay ra một promise mới và promise mới này sẽ chứa kết quả của promise được kết thúc đầu tiên.
-
- -
-
{{jsxref("Promise.reject", "Promise.reject(reason)")}}
-
Trả ra một promise trạng thái lỗi với mã lỗi mà hàm xử lý trả ra. Hàm này sẽ được gọi tới khi hàm xử lý của ta bị lỗi (thất bại).
-
- -
-
{{jsxref("Promise.resolve", "Promise.resolve(value)")}}
-
Trả ra một promise thành công với kết quả mà hàm xử lý trả ra. 
-
- -

Nguyên mẫu Promise

- -

Thuộc tính

- -

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

- -

Phương thức

- -

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

- -

Ví dụ

- -

Tạo một Promise

- - - -

Ví dụ nhỏ này sẽ mô tả cơ chế của một Promise. Hàm testPromise() sẽ được gọi tới mỗi khi ta click vào {{HTMLElement("button")}}. Ta sẽ sử dụng {{domxref("window.setTimeout()")}} để thiết lập giá trị kết thúc cho nó. Hàm xử lý này sẽ đếm (bắt đầu từ 1) sau mỗi khoảng thời gian ngẫu nhiên từ 1 tới 3 giây.

- -

Hàm hậu xử lý đính kèm ở đây chỉ đơn giản là một hàm log lại các giá trị được trả ra và được gán bằng cách sử dụng hàm {{jsxref("Promise.prototype.then()","p1.then()")}}.

- -
'use strict';
-var promiseCount = 0;
-
-function testPromise() {
-    var thisPromiseCount = ++promiseCount;
-
-    var log = document.getElementById('log');
-    log.insertAdjacentHTML('beforeend', thisPromiseCount +
-        ') Started (<small>Sync code started</small>)<br/>');
-
-    // Tạo một Promise: we promise a numeric count of this promise, starting from 1 (after waiting 3s)
-    var p1 = new Promise(
-        // The resolver function is called with the ability to resolve or
-        // reject the promise
-        function(resolve, reject) {
-            log.insertAdjacentHTML('beforeend', thisPromiseCount +
-                ') Promise started (<small>Async code started</small>)<br/>');
-            // This is only an example to create asynchronism
-            window.setTimeout(
-                function() {
-                    // We fulfill the promise !
-                    resolve(thisPromiseCount);
-                }, Math.random() * 2000 + 1000);
-        }
-    );
-
-    // We define what to do when the promise is resolved/fulfilled with the then() call,
-    // and the catch() method defines what to do if the promise is rejected.
-    p1.then(
-        // Log the fulfillment value
-        function(val) {
-            log.insertAdjacentHTML('beforeend', val +
-                ') Promise fulfilled (<small>Async code terminated</small>)<br/>');
-        })
-    .catch(
-        // Log the rejection reason
-        function(reason) {
-            console.log('Handle rejected promise ('+reason+') here.');
-        });
-
-    log.insertAdjacentHTML('beforeend', thisPromiseCount +
-        ') Promise made (<small>Sync code terminated</small>)<br/>');
-}
- - - -

Ví dụ này được thực thi mỗi khi ta click vào button và để chạy được ví dụ này, bạn cần một trình duyệt có hỗ trợ Promise. Bạn hãy thử click vào button một vài lần liên tiếp trong một khoảng thời gian ngắn để thấy được các promise được xử lý thành chuỗi và sau khi kết thúc xử lý sẽ ở trạng thái thế nào nhé.

- -

{{EmbedLiveSample("Creating_a_Promise", "500", "200")}}

- -

Ví dụ với XMLHttpRequest

- -

Tạo một Promise

- -

Ví dụ này sẽ trình bày một cách sử dụng Promise để lấy kết quả (thành công hoặc lỗi) trả về từ {{domxref("XMLHttpRequest")}}.

- -
'use strict';
-
-// A-> $http function is implemented in order to follow the standard Adapter pattern
-function $http(url){
-
-  // A small example of object
-  var core = {
-
-    // Method that performs the ajax request
-    ajax: function (method, url, args) {
-
-      // Creating a promise
-      var promise = new Promise( function (resolve, reject) {
-
-        // Instantiates the XMLHttpRequest
-        var client = new XMLHttpRequest();
-        var uri = url;
-
-        if (args && (method === 'POST' || method === 'PUT')) {
-          uri += '?';
-          var argcount = 0;
-          for (var key in args) {
-            if (args.hasOwnProperty(key)) {
-              if (argcount++) {
-                uri += '&';
-              }
-              uri += encodeURIComponent(key) + '=' + encodeURIComponent(args[key]);
-            }
-          }
-        }
-
-        client.open(method, uri);
-        client.send();
-
-        client.onload = function () {
-          if (this.status >= 200 && this.status < 300) {
-            // Performs the function "resolve" when this.status is equal to 2xx
-            resolve(this.response);
-          } else {
-            // Performs the function "reject" when this.status is different than 2xx
-            reject(this.statusText);
-          }
-        };
-        client.onerror = function () {
-          reject(this.statusText);
-        };
-      });
-
-      // Return the promise
-      return promise;
-    }
-  };
-
-  // Adapter pattern
-  return {
-    'get': function(args) {
-      return core.ajax('GET', url, args);
-    },
-    'post': function(args) {
-      return core.ajax('POST', url, args);
-    },
-    'put': function(args) {
-      return core.ajax('PUT', url, args);
-    },
-    'delete': function(args) {
-      return core.ajax('DELETE', url, args);
-    }
-  };
-};
-// End A
-
-// B-> Here you define its functions and its payload
-var mdnAPI = 'https://developer.mozilla.org/en-US/search.json';
-var payload = {
-  'topic' : 'js',
-  'q'     : 'Promise'
-};
-
-var callback = {
-  success: function(data) {
-    console.log(1, 'success', JSON.parse(data));
-  },
-  error: function(data) {
-    console.log(2, 'error', JSON.parse(data));
-  }
-};
-// End B
-
-// Executes the method call
-$http(mdnAPI)
-  .get(payload)
-  .then(callback.success)
-  .catch(callback.error);
-
-// Executes the method call but an alternative way (1) to handle Promise Reject case
-$http(mdnAPI)
-  .get(payload)
-  .then(callback.success, callback.error);
-
-// Executes the method call but an alternative way (2) to handle Promise Reject case
-$http(mdnAPI)
-  .get(payload)
-  .then(callback.success)
-  .then(undefined, callback.error);
-
- -

Tải một ảnh với XHR

- -

Một ví dụ đơn giản khác được sử dụng Promise và XMLHttpRequest để tải về một ảnh là MDN  GitHub - promise-test. Ngoài ra, bạn có thể xem nó hoạt động ra sao tại đây. Mỗi bước đều được chú thích đầy đủ để giúp bạn hình dung được việc sử dụng Promise với XHR dễ dàng hơn.

- -

Mô tả

- - - - - - - - - - - - - - - - - - - -
Mô tảTrạng tháiChú thích
{{SpecName('ES6', '#sec-promise-objects', 'Promise')}}{{Spec2('ES6')}}Initial definition in an ECMA standard.
{{SpecName('ESDraft', '#sec-promise-objects', 'Promise')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- - - -

{{Compat}}

- -

Tham khảo thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/regexp/exec/index.html b/files/vi/web/javascript/reference/global_objects/regexp/exec/index.html deleted file mode 100644 index 9fdf5c193e..0000000000 --- a/files/vi/web/javascript/reference/global_objects/regexp/exec/index.html +++ /dev/null @@ -1,194 +0,0 @@ ---- -title: RegExp.prototype.exec() -slug: Web/JavaScript/Reference/Global_Objects/RegExp/exec -tags: - - Biểu thức chính quy - - Phương Thức - - Tham khảo -translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/exec ---- -
{{JSRef}}
- -

Phương thức exec() tiến hành tìm kiếm một so khớp trong một chuỗi xác định. Trả về một mảng kết quả hoặc {{jsxref("null")}}.

- -

Nếu bạn đơn giản chỉ muốn xác định có khớp hay không, tức kết quả trả về là true hoặc false, bạn nên sử dụng phương thức {{jsxref("RegExp.prototype.test()")}} hoặc phương thức {{jsxref("String.prototype.search()")}}.

- -
{{EmbedInteractiveExample("pages/js/regexp-prototype-exec.html")}}
- - - -

Cú pháp

- -
regexObj.exec(str)
- -

Tham số

- -
-
str
-
Chuỗi dùng để so khớp với biểu thức chính quy.
-
- -

Giá trị trả về

- -

Nếu so khớp thành công, phương thức exec() trả về một mảng và cập nhật các thuộc tính của đối tượng biểu thức chính quy. Mảng trả về item đầu tiên là đoạn text khớp, và các item tiếp theo là giá trị trong các dấu ngoặc tròn có nhớ đã khớp.

- -

Nếu việc so khớp thất bại, exec() trả về  {{jsxref("null")}}.

- -

Mô tả

- -

Hãy xem xét ví dụ sau:

- -
// So khớp "quick brown" theo sau bởi "jumps", bỏ qua các kí tự ở giữa
-// Nhớ "brown" và "jumps"
-// Không phân biệt chữ hoa/thường
-var re = /quick\s(brown).+?(jumps)/ig;
-var result = re.exec('The Quick Brown Fox Jumps Over The Lazy Dog');
-
- -

Bảng dưới đây là kết quả trả về của so khớp trên.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đối tượngThuộc tính/Chỉ mụcMô tảVí dụ
result[0]Chuỗi đầy đủ của các kí tự đã khớp.Quick Brown Fox Jumps
[1], ...[n ] -

Các chuỗi con khớp được đặt trong ngoặc, nếu có. Số lượng ngoặc không giới hạn.

-
[1] = Brown
- [2] = Jumps
index -

Chỉ mục (tính từ 0) của bản khớp trong chuỗi.

-
4
inputChuỗi ban đầu.The Quick Brown Fox Jumps Over The Lazy Dog
relastIndex -

Chỉ mục bắt đầu tìm so khớp tiếp theo. Khi không có cờ "g" thì chỉ mục sẽ trở về 0.

-
25
ignoreCaseXác định xem liệu cờ "i" (không phân biệt chữ hoa/thường) được sử dụng hay không.true
globalXác định liệu cờ "g" (so khớp toàn cục) có được sử dụng hay không.true
multilineXác định xem cờ "m" (tìm kiếm chuỗi đa dòng) có được sử dụng hay không.false
sourcemẫu dùng để so khớp.quick\s(brown).+?(jumps)
- -

Ví dụ

- -

Tìm các so khớp tiếp theo

- -

Nếu biểu thức chính quy của bạn sử dụng cờ g, bạn có thể dùng phương thức exec() nhiều lần để tìm các so khớp tiếp theo trong chuỗi giống vậy. Lúc đó, việc tìm kếu bắt đầu từ chuỗi con của str đã được chỉ định bởi thuộc tính {{jsxref("RegExp.lastIndex", "lastIndex")}} của biểu thức chính quy. ({{jsxref("RegExp.prototype.test()", "test()")}} cũng sẽ tăng tới thuộc tính {{jsxref("RegExp.lastIndex", "lastIndex")}} property. Ví dụ, giả sử bạn có kịch bản:

- -
var myRe = /ab*/g;
-var str = 'abbcdefabh';
-var myArray;
-while ((myArray = myRe.exec(str)) !== null) {
-  var msg = 'Found ' + myArray[0] + '. ';
-  msg += 'Next match starts at ' + myRe.lastIndex;
-  console.log(msg);
-}
-
- -

Kịch bản này hiển thị văn bản sau:

- -
Found abb. Next match starts at 3
-Found ab. Next match starts at 9
-
- -

Chú ý: Đừng đặt biểu thức chính quy thuần (hoặc cấu trúc {{jsxref("RegExp")}}) bên trong điều kiện while hoặc nó sẽ tạo ra một vòng lặp vĩnh cửu nếu có một so khớp vì thuộc tính {{jsxref("RegExp.lastIndex", "lastIndex")}} sẽ reset lại sau mỗi vòng lặp. Và hãy chắc rằng cờ toàn cùng được xét nếu không một vòng lặp sẽ xảy ra.

- -

Sử dụng exec() với RegExp thuần

- -

Bạn có thể sử dụng exec() mà không cần tạo đối tượng {{jsxref("RegExp")}}:

- -
var matches = /(hello \S+)/.exec('This is a hello world!');
-console.log(matches[1]);
-
- -

Kịch bản này sẽ ghi ra lời nhắn chứa 'hello world!'.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.10.6.21', 'RegExp.exec')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-regexp.prototype.exec', 'RegExp.exec')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-regexp.prototype.exec', 'RegExp.exec')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
- - -

{{Compat("javascript.builtins.RegExp.exec")}}

-
- -

See also

- - diff --git a/files/vi/web/javascript/reference/global_objects/regexp/index.html b/files/vi/web/javascript/reference/global_objects/regexp/index.html deleted file mode 100644 index 01f9b60832..0000000000 --- a/files/vi/web/javascript/reference/global_objects/regexp/index.html +++ /dev/null @@ -1,618 +0,0 @@ ---- -title: RegExp -slug: Web/JavaScript/Reference/Global_Objects/RegExp -tags: - - Constructor - - JavaScript - - NeedsTranslation - - Reference - - RegExp - - Regular Expressions - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/RegExp ---- -
{{JSRef}}
- -

The RegExp constructor creates a regular expression object for matching text with a pattern.

- -

For an introduction to regular expressions, read the Regular Expressions chapter in the JavaScript Guide.

- -
{{EmbedInteractiveExample("pages/js/regexp-constructor.html")}}
- - - -

Syntax

- -

Literal, constructor, and factory notations are possible:

- -
/pattern/flags
-new RegExp(pattern[, flags])
-RegExp(pattern[, flags])
-
- -

Parameters

- -
-
pattern
-
The text of the regular expression.
-
flags
-
-

If specified, flags can have any combination of the following values:

- -
-
g
-
global match; find all matches rather than stopping after the first match
-
i
-
ignore case; if u flag is also enabled, use Unicode case folding
-
m
-
multiline; treat beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string)
-
u
-
Unicode; treat pattern as a sequence of Unicode code points
-
y
-
sticky; matches only from the index indicated by the lastIndex property of this regular expression in the target string (and does not attempt to match from any later indexes).
-
-
-
- -

Description

- -

There are 2 ways to create a RegExp object: a literal notation and a constructor. To indicate strings, the parameters to the literal notation do not use quotation marks while the parameters to the constructor function do use quotation marks. So the following expressions create the same regular expression:

- -
/ab+c/i;
-new RegExp('ab+c', 'i');
-new RegExp(/ab+c/, 'i');
-
- -

The literal notation provides a compilation of the regular expression when the expression is evaluated. Use literal notation when the regular expression will remain constant. For example, if you use literal notation to construct a regular expression used in a loop, the regular expression won't be recompiled on each iteration.

- -

The constructor of the regular expression object, for example, new RegExp('ab+c'), provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.

- -

Starting with ECMAScript 6, new RegExp(/ab+c/, 'i') no longer throws a {{jsxref("TypeError")}} ("can't supply flags when constructing one RegExp from another") when the first argument is a RegExp and the second flags argument is present. A new RegExp from the arguments is created instead.

- -

When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary. For example, the following are equivalent:

- -
var re = /\w+/;
-var re = new RegExp('\\w+');
-
- -

Special characters meaning in regular expressions

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Character Classes
CharacterMeaning
. -

(The dot, the decimal point) matches any single character except line terminators: \n, \r, \u2028 or \u2029.

- -

Inside a character set, the dot loses its special meaning and matches a literal dot.

- -

Note that the m multiline flag doesn't change the dot behavior. So to match a pattern across multiple lines, the character set [^] can be used (if you don't mean an old version of IE, of course), it will match any character including newlines.

- -

For example, /.y/ matches "my" and "ay", but not "yes", in "yes make my day".

-
\d -

Matches any digit (Arabic numeral). Equivalent to [0-9].

- -

For example, /\d/ or /[0-9]/ matches "2" in "B2 is the suite number".

-
\D -

Matches any character that is not a digit (Arabic numeral). Equivalent to [^0-9].

- -

For example, /\D/ or /[^0-9]/ matches "B" in "B2 is the suite number".

-
\w -

Matches any alphanumeric character from the basic Latin alphabet, including the underscore. Equivalent to [A-Za-z0-9_].

- -

For example, /\w/ matches "a" in "apple", "5" in "$5.28", and "3" in "3D".

-
\W -

Matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_].

- -

For example, /\W/ or /[^A-Za-z0-9_]/ matches "%" in "50%".

-
\s -

Matches a single white space character, including space, tab, form feed, line feed and other Unicode spaces. Equivalent to [ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff].

- -

For example, /\s\w*/ matches " bar" in "foo bar".

-
\S -

Matches a single character other than white space. Equivalent to [^ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff].

- -

For example, /\S\w*/ matches "foo" in "foo bar".

-
\tMatches a horizontal tab.
\rMatches a carriage return.
\nMatches a linefeed.
\vMatches a vertical tab.
\fMatches a form-feed.
[\b]Matches a backspace. (Not to be confused with \b)
\0Matches a NUL character. Do not follow this with another digit.
\cX -

Where X is a letter from A - Z. Matches a control character in a string.

- -

For example, /\cM/ matches control-M in a string.

-
\xhhMatches the character with the code hh (two hexadecimal digits).
\uhhhhMatches a UTF-16 code-unit with the value hhhh (four hexadecimal digits).
\u{hhhh} or \u{hhhhh}(only when u flag is set) Matches the character with the Unicode value U+hhhh or U+hhhhh (hexadecimal digits).
\ -

For characters that are usually treated literally, indicates that the next character is special and not to be interpreted literally.

- -

For example, /b/ matches the character "b". By placing a backslash in front of "b", that is by using /\b/, the character becomes special to mean match a word boundary.

- -

or

- -

For characters that are usually treated specially, indicates that the next character is not special and should be interpreted literally.

- -

For example, "*" is a special character that means 0 or more occurrences of the preceding character should be matched; for example, /a*/ means match 0 or more "a"s. To match * literally, precede it with a backslash; for example, /a\*/ matches "a*".

-
Character Sets
CharacterMeaning
[xyz]
- [a-c]
-

A character set. Matches any one of the enclosed characters. You can specify a range of characters by using a hyphen, but if the hyphen appears as the first or last character enclosed in the square brackets it is taken as a literal hyphen to be included in the character set as a normal character. It is also possible to include a character class in a character set.

- -

For example, [abcd] is the same as [a-d]. They match the "b" in "brisket" and the "c" in "chop".

- -

For example, [abcd-] and [-abcd] match the "b" in "brisket", the "c" in "chop" and the "-" (hyphen) in "non-profit".

- -

For example, [\w-] is the same as [A-Za-z0-9_-]. They match the "b" in "brisket", the "c" in "chop" and the "n" in "non-profit".

-
-

[^xyz]
- [^a-c]

-
-

A negated or complemented character set. That is, it matches anything that is not enclosed in the brackets. You can specify a range of characters by using a hyphen, but if the hyphen appears as the first or last character enclosed in the square brackets it is taken as a literal hyphen to be included in the character set as a normal character.

- -

For example, [^abc] is the same as [^a-c]. They initially match "o" in "bacon" and "h" in "chop".

-
Alternation
CharacterMeaning
x|y -

Matches either x or y.

- -

For example, /green|red/ matches "green" in "green apple" and "red" in "red apple".

-
Boundaries
CharacterMeaning
^ -

Matches beginning of input. If the multiline flag is set to true, also matches immediately after a line break character.

- -

For example, /^A/ does not match the "A" in "an A", but does match the first "A" in "An A".

-
$ -

Matches end of input. If the multiline flag is set to true, also matches immediately before a line break character.

- -

For example, /t$/ does not match the "t" in "eater", but does match it in "eat".

-
\b -

Matches a word boundary. This is the position where a word character is not followed or preceded by another word-character, such as between a letter and a space. Note that a matched word boundary is not included in the match. In other words, the length of a matched word boundary is zero.

- -

Examples:
- /\bm/ matches the 'm' in "moon" ;
- /oo\b/ does not match the 'oo' in "moon", because 'oo' is followed by 'n' which is a word character;
- /oon\b/ matches the 'oon' in "moon", because 'oon' is the end of the string, thus not followed by a word character;
- /\w\b\w/ will never match anything, because a word character can never be followed by both a non-word and a word character.

-
\B -

Matches a non-word boundary. This is a position where the previous and next character are of the same type: Either both must be words, or both must be non-words. Such as between two letters or between two spaces. The beginning and end of a string are considered non-words. Same as the matched word boundary, the matched non-word bondary is also not included in the match.

- -

For example, /\Bon/ matches "on" in "at noon", and /ye\B/ matches "ye" in "possibly yesterday".

-
Grouping and back references
CharacterMeaning
(x) -

Matches x and remembers the match. These are called capturing groups.

- -

For example, /(foo)/ matches and remembers "foo" in "foo bar". 

- -

The capturing groups are numbered according to the order of left parentheses of capturing groups, starting from 1. The matched substring can be recalled from the resulting array's elements [1], ..., [n] or from the predefined RegExp object's properties $1, ..., $9.

- -

Capturing groups have a performance penalty. If you don't need the matched substring to be recalled, prefer non-capturing parentheses (see below).

-
\n -

Where n is a positive integer. A back reference to the last substring matching the n parenthetical in the regular expression (counting left parentheses).

- -

For example, /apple(,)\sorange\1/ matches "apple, orange," in "apple, orange, cherry, peach". A complete example follows this table.

-
(?:x)Matches x but does not remember the match. These are called non-capturing groups. The matched substring cannot be recalled from the resulting array's elements [1], ..., [n] or from the predefined RegExp object's properties $1, ..., $9.
Quantifiers
CharacterMeaning
x* -

Matches the preceding item x 0 or more times.

- -

For example, /bo*/ matches "boooo" in "A ghost booooed" and "b" in "A bird warbled", but nothing in "A goat grunted".

-
x+ -

Matches the preceding item x 1 or more times. Equivalent to {1,}.

- -

For example, /a+/ matches the "a" in "candy" and all the "a"'s in "caaaaaaandy".

-
x? -

Matches the preceding item x 0 or 1 time.

- -

For example, /e?le?/ matches the "el" in "angel" and the "le" in "angle."

- -

If used immediately after any of the quantifiers *, +, ?, or {}, makes the quantifier non-greedy (matching the minimum number of times), as opposed to the default, which is greedy (matching the maximum number of times).

-
x{n} -

Where n is a positive integer. Matches exactly n occurrences of the preceding item x.

- -

For example, /a{2}/ doesn't match the "a" in "candy", but it matches all of the "a"'s in "caandy", and the first two "a"'s in "caaandy".

-
x{n,} -

Where n is a positive integer. Matches at least n occurrences of the preceding item x.

- -

For example, /a{2,}/ doesn't match the "a" in "candy", but matches all of the a's in "caandy" and in "caaaaaaandy".

-
x{n,m} -

Where n is 0 or a positive integer, and m is a positive integer. Matches at least n and at most m occurrences of the preceding item x.

- -

For example, /a{1,3}/ matches nothing in "cndy", the "a" in "candy", the two "a"'s in "caandy", and the first three "a"'s in "caaaaaaandy". Notice that when matching "caaaaaaandy", the match is "aaa", even though the original string had more "a"'s in it.

-
-

x*?
- x+?
- x??
- x{n}?
- x{n,}?
- x{n,m}?

-
-

Matches the preceding item x like *, +, ?, and {...} from above, however the match is the smallest possible match.

- -

For example, /<.*?>/ matches "<foo>" in "<foo> <bar>", whereas /<.*>/ matches "<foo> <bar>".

- -

Quantifiers without ? are said to be greedy. Those with ? are called "non-greedy".

-
Assertions
CharacterMeaning
x(?=y) -

Matches x only if x is followed by y.

- -

For example, /Jack(?=Sprat)/ matches "Jack" only if it is followed by "Sprat".
- /Jack(?=Sprat|Frost)/ matches "Jack" only if it is followed by "Sprat" or "Frost". However, neither "Sprat" nor "Frost" is part of the match results.

-
x(?!y) -

Matches x only if x is not followed by y.

- -

For example, /\d+(?!\.)/ matches a number only if it is not followed by a decimal point.
- /\d+(?!\.)/.exec('3.141') matches "141" but not "3.141".

-
- -

Properties

- -
-
{{jsxref("RegExp.prototype")}}
-
Allows the addition of properties to all objects.
-
RegExp.length
-
The value of RegExp.length is 2.
-
{{jsxref("RegExp.@@species", "get RegExp[@@species]")}}
-
The constructor function that is used to create derived objects.
-
{{jsxref("RegExp.lastIndex")}}
-
The index at which to start the next match.
-
- -

Methods

- -

The global RegExp object has no methods of its own, however, it does inherit some methods through the prototype chain.

- -

RegExp prototype objects and instances

- -

Properties

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

Methods

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

Examples

- -

Using a regular expression to change data format

- -

The following script uses the {{jsxref("String.prototype.replace()", "replace()")}} method of the {{jsxref("Global_Objects/String", "String")}} instance to match a name in the format first last and output it in the format last, first. In the replacement text, the script uses $1 and $2 to indicate the results of the corresponding matching parentheses in the regular expression pattern.

- -
var re = /(\w+)\s(\w+)/;
-var str = 'John Smith';
-var newstr = str.replace(re, '$2, $1');
-console.log(newstr);
-
- -

This displays "Smith, John".

- -

Using regular expression to split lines with different line endings/ends of line/line breaks

- -

The default line ending varies depending on the platform (Unix, Windows, etc.). The line splitting provided in this example works on all platforms.

- -
var text = 'Some text\nAnd some more\r\nAnd yet\rThis is the end';
-var lines = text.split(/\r\n|\r|\n/);
-console.log(lines); // logs [ 'Some text', 'And some more', 'And yet', 'This is the end' ]
-
- -

Note that the order of the patterns in the regular expression matters.

- -

Using regular expression on multiple lines

- -
var s = 'Please yes\nmake my day!';
-s.match(/yes.*day/);
-// Returns null
-s.match(/yes[^]*day/);
-// Returns ["yes\nmake my day"]
-
- -

Using a regular expression with the sticky flag

- -

The sticky flag indicates that the regular expression performs sticky matching in the target string by attempting to match starting at {{jsxref("RegExp.prototype.lastIndex")}}.

- -
var str = '#foo#';
-var 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)
- -

Regular expression and Unicode characters

- -

As mentioned above, \w or \W only matches ASCII based characters; for example, "a" to "z", "A" to "Z", "0" to "9" and "_". To match characters from other languages such as Cyrillic or Hebrew, use \uhhhh, where "hhhh" is the character's Unicode value in hexadecimal. This example demonstrates how one can separate out Unicode characters from a word.

- -
var text = 'Образец text на русском языке';
-var regex = /[\u0400-\u04FF]+/g;
-
-var match = regex.exec(text);
-console.log(match[0]);        // logs 'Образец'
-console.log(regex.lastIndex); // logs '7'
-
-var match2 = regex.exec(text);
-console.log(match2[0]);       // logs 'на' [did not log 'text']
-console.log(regex.lastIndex); // logs '15'
-
-// and so on
-
- -

Here's an external resource for getting the complete Unicode block range for different scripts: Regexp-Unicode-block.

- -

Extracting sub-domain name from URL

- -
var url = 'http://xxx.domain.com';
-console.log(/[^.]+/.exec(url)[0].substr(7)); // logs 'xxx'
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.1.
{{SpecName('ES5.1', '#sec-15.10', 'RegExp')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-regexp-regular-expression-objects', 'RegExp')}}{{Spec2('ES6')}}The RegExp constructor no longer throws when the first argument is a RegExp and the second argument is present. Introduces Unicode and sticky flags.
{{SpecName('ESDraft', '#sec-regexp-regular-expression-objects', 'RegExp')}}{{Spec2('ESDraft')}} 
- -

Browser compatibility

- -
- - -

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

-
- -

Firefox-specific notes

- -

Starting with Firefox 34, in the case of a capturing group with quantifiers preventing its exercise, the matched text for a capturing group is now undefined instead of an empty string:

- -
// Firefox 33 or older
-'x'.replace(/x(.)?/g, function(m, group) {
-  console.log("'group:" + group + "'");
-}); // 'group:'
-
-// Firefox 34 or newer
-'x'.replace(/x(.)?/g, function(m, group) {
-  console.log("'group:" + group + "'");
-}); // 'group:undefined'
-
- -

Note that due to web compatibility, RegExp.$N will still return an empty string instead of undefined ({{bug(1053944)}}).

- -

See also

- - diff --git a/files/vi/web/javascript/reference/global_objects/string/index.html b/files/vi/web/javascript/reference/global_objects/string/index.html deleted file mode 100644 index c9f5680a0c..0000000000 --- a/files/vi/web/javascript/reference/global_objects/string/index.html +++ /dev/null @@ -1,405 +0,0 @@ ---- -title: String -slug: Web/JavaScript/Reference/Global_Objects/String -tags: - - ECMAScript6 - - JavaScript - - NeedsTranslation - - Reference - - String - - TopicStub -translation_of: Web/JavaScript/Reference/Global_Objects/String ---- -
{{JSRef}}
-

lnyannini

- -

HTML

- -
Nội dung HTML mẫu
- -

CSS

- -
Nội dung CSS mẫu
- -

JavaScript

- -
Nội dung JavaScript mẫu
- -

Kết quả

- -

{{EmbedLiveSample('lnyannini')}}

-f}} - -

Copy dtoc: june-12-2017
- The String global object is a constructor for strings, or a sequence of characters.
- Đối tượng Chuỗi toàn cục là một constructor cho chuỗi, hoặc chuỗi ký tự.

- -

Syntax

- -

String literals take the forms:

- -
'string text'
-"string text"
-"中文 español deutsch English हिन्दी العربية português বাংলা русский 日本語 ਪੰਜਾਬੀ 한국어 தமிழ் עברית"
- -

Strings can also be created using the String global object directly:

- -
String(thing)
- -

Parameters

- -
-
thing
-
Anything to be converted to a string.
-
- -

Template literals

- -

Starting with ECMAScript 2015, string literals can also be so-called Template literals:
- Trong ES6 Chuỗi cũng được gọi là Template Strings.

- -
`hello world`
-`hello!
- world!`
-`hello ${who}`
-escape `<a>${who}</a>`
- -
-
- -

Escape notation

- -

Beside regular, printable characters, special characters can be encoded using escape notation:
- Ngoài ký tự thường, các ký tự đặc biệt có thể được code ra bằng cách dùng các ký hiệu loại trừ:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
CodeOutput
\0the NULL character
\'single quote
\"double quote
\\backslash
\nnew line
\rcarriage return
\vvertical tab
\ttab
\bbackspace
\fform feed
\uXXXXunicode codepoint
\u{X} ... \u{XXXXXX}unicode codepoint {{experimental_inline}}
\xXXthe Latin-1 character
- -
-

Unlike some other languages, JavaScript makes no distinction between single-quoted strings and double-quoted strings; therefore, the escape sequences above work in strings created with either single or double quotes.

-
- -
-
- -

Long literal strings

- -

Sometimes, your code will include strings which are very long. Rather than having lines that go on endlessly, or wrap at the whim of your editor, you may wish to specifically break the string into multiple lines in the source code without affecting the actual string contents. There are two ways you can do this.

- -

You can use the + operator to append multiple strings together, like this:

- -
let longString = "This is a very long string which needs " +
-                 "to wrap across multiple lines because " +
-                 "otherwise my code is unreadable.";
-
- -

Or you can use the backslash character ("\") at the end of each line to indicate that the string will continue on the next line. Make sure there is no space or any other character after the backslash (except for a line break), or as an indent; otherwise it will not work. That form looks like this:

- -
let longString = "This is a very long string which needs \
-to wrap across multiple lines because \
-otherwise my code is unreadable.";
-
- -

Both of these result in identical strings being created.

- -

Description

- -

Strings are useful for holding data that can be represented in text form. Some of the most-used operations on strings are to check their {{jsxref("String.length", "length")}}, to build and concatenate them using the + and += string operators, checking for the existence or location of substrings with the {{jsxref("String.prototype.indexOf()", "indexOf()")}} method, or extracting substrings with the {{jsxref("String.prototype.substring()", "substring()")}} method.

- -

Character access

- -

There are two ways to access an individual character in a string. The first is the {{jsxref("String.prototype.charAt()", "charAt()")}} method:

- -
return 'cat'.charAt(1); // returns "a"
-
- -

The other way (introduced in ECMAScript 5) is to treat the string as an array-like object, where individual characters correspond to a numerical index:

- -
return 'cat'[1]; // returns "a"
-
- -

For character access using bracket notation, attempting to delete or assign a value to these properties will not succeed. The properties involved are neither writable nor configurable. (See {{jsxref("Object.defineProperty()")}} for more information.)

- -

Comparing strings

- -

C developers have the strcmp() function for comparing strings. In JavaScript, you just use the less-than and greater-than operators:

- -
var a = 'a';
-var b = 'b';
-if (a < b) { // true
-  console.log(a + ' is less than ' + b);
-} else if (a > b) {
-  console.log(a + ' is greater than ' + b);
-} else {
-  console.log(a + ' and ' + b + ' are equal.');
-}
-
- -

A similar result can be achieved using the {{jsxref("String.prototype.localeCompare()", "localeCompare()")}} method inherited by String instances.

- -

Distinction between string primitives and String objects

- -

Note that JavaScript distinguishes between String objects and primitive string values. (The same is true of {{jsxref("Boolean")}} and {{jsxref("Global_Objects/Number", "Numbers")}}.)

- -

String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the {{jsxref("Operators/new", "new")}} keyword) are primitive strings. JavaScript automatically converts primitives to String objects, so that it's possible to use String object methods for primitive strings. In contexts where a method is to be invoked on a primitive string or a property lookup occurs, JavaScript will automatically wrap the string primitive and call the method or perform the property lookup.

- -
var s_prim = 'foo';
-var s_obj = new String(s_prim);
-
-console.log(typeof s_prim); // Logs "string"
-console.log(typeof s_obj);  // Logs "object"
-
- -

String primitives and String objects also give different results when using {{jsxref("Global_Objects/eval", "eval()")}}. Primitives passed to eval are treated as source code; String objects are treated as all other objects are, by returning the object. For example:

- -
var s1 = '2 + 2';             // creates a string primitive
-var s2 = new String('2 + 2'); // creates a String object
-console.log(eval(s1));        // returns the number 4
-console.log(eval(s2));        // returns the string "2 + 2"
-
- -

For these reasons, code may break when it encounters String objects when it expects a primitive string instead, although generally authors need not worry about the distinction.

- -

A String object can always be converted to its primitive counterpart with the {{jsxref("String.prototype.valueOf()", "valueOf()")}} method.

- -
console.log(eval(s2.valueOf())); // returns the number 4
-
- -
Note: For another possible approach to strings in JavaScript, please read the article about StringView — a C-like representation of strings based on typed arrays.
- -

Properties

- -
-
{{jsxref("String.prototype")}}
-
Allows the addition of properties to a String object.
-
- -

Methods

- -
-
{{jsxref("String.fromCharCode()")}}
-
Returns a string created by using the specified sequence of Unicode values.
-
{{jsxref("String.fromCodePoint()")}} {{experimental_inline}}
-
Returns a string created by using the specified sequence of code points.
-
{{jsxref("String.raw()")}} {{experimental_inline}}
-
Returns a string created from a raw template string.
-
- -

String generic methods

- -
-

String generics are non-standard, deprecated and will get removed near future.

-
- -

The String instance methods are also available in Firefox as of JavaScript 1.6 (not part of the ECMAScript standard) on the String object for applying String methods to any object:

- -
var num = 15;
-console.log(String.replace(num, /5/, '2'));
-
- -

For migrating away from String generics, see also Warning: String.x is deprecated; use String.prototype.x instead.

- -

{{jsxref("Global_Objects/Array", "Generics", "#Array_generic_methods", 1)}} are also available on {{jsxref("Array")}} methods.

- -

String instances

- -

Properties

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

Methods

- -

Methods unrelated to HTML

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'Methods_unrelated_to_HTML')}}
- -

HTML wrapper methods

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/prototype', 'HTML_wrapper_methods')}}
- -

Examples

- -

String conversion

- -

It's possible to use String as a "safer" {{jsxref("String.prototype.toString()", "toString()")}} alternative, although it still normally calls the underlying toString(). It also works for {{jsxref("null")}}, {{jsxref("undefined")}}, and for {{jsxref("Symbol", "symbols")}}. For example:

- -
var outputStrings = [];
-for (var i = 0, n = inputValues.length; i < n; ++i) {
-  outputStrings.push(String(inputValues[i]));
-}
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Initial definition.
{{SpecName('ES5.1', '#sec-15.5', 'String')}}{{Spec2('ES5.1')}}
{{SpecName('ES2015', '#sec-string-objects', 'String')}}{{Spec2('ES2015')}}
{{SpecName('ESDraft', '#sec-string-objects', 'String')}}{{Spec2('ESDraft')}}
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
\u{XXXXXX}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatGeckoDesktop("40")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
\u{XXXXXX}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("40")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

See also

- - diff --git a/files/vi/web/javascript/reference/global_objects/string/match/index.html b/files/vi/web/javascript/reference/global_objects/string/match/index.html deleted file mode 100644 index d40ffc4482..0000000000 --- a/files/vi/web/javascript/reference/global_objects/string/match/index.html +++ /dev/null @@ -1,160 +0,0 @@ ---- -title: String.prototype.match() -slug: Web/JavaScript/Reference/Global_Objects/String/match -tags: - - Biểu thức chính quy - - Chuỗi - - Phương Thức -translation_of: Web/JavaScript/Reference/Global_Objects/String/match ---- -
{{JSRef}}
- -
 
- -

Phương thức match() đưa ra những so khớp khi so khớp một chuỗi (string) với biểu thức chính quy.

- -

Cú pháp

- -
str.match(regexp)
- -

Tham số

- -
-
regexp
-
Đối tượng biểu thức chính quy.  Nếu một đối tượng obj không phải biểu thức chính quy được truyền vào, nó sẽ ngầm chuyển đổi thành một {{jsxref("RegExp")}} bằng cách sử dụng new RegExp(obj). Nếu bạn không truyền tham số và sử dụng trực tiếp phương thức match(), bạn sẽ nhận lại một {{jsxref("Array")}} với một chuỗi rỗng: [""].
-
- -

Giá trị trả về

- -

Nếu một chuỗi khớp với biểu thức, nó sẽ trả lại một {{jsxref("Array")}} chứa chuỗi khớp hoàn toàn là phần tử đầu tiên, tiếp đó là các kết quả nằm trong dấu ngoặc đơn (ngoặc có nhớ). Nếu không có so khớp, nó sẽ trả về {{jsxref("null")}}.

- -

Mô tả

- -

Nếu một biểu thức chính quy không có cờ gstr.match() trả về kết quả giống như  {{jsxref("RegExp.prototype.exec()", "RegExp.exec()")}}. {{jsxref("Array")}} trả về có thêm thuộc tính input chứa chuỗi ban đầu được phân tích ngữ pháp. Thêm nữa, nó có một thuộc tính index đại diện cho chỉ mục (tính từ 0) của so khớp trong chuỗi.

- -

Nếu biểu thức chính quy có cờ g, phương thức trả về một {{jsxref("Array")}} chứa tất cả chuỗi con khớp mà không phải các đối tượng khớp. Nó không trả về chuỗi trong dấu ngoặc tròn có nhớ. Nếu không có so khớp, phương thức trả về {{jsxref("null")}}.

- -

Xem thêm: Các phương thức RegEx

- - - -

Ví dụ

- -

Sử dụng match()

- -

Trong ví dụ dưới đây, match() được dùng để tìm chuỗi 'Chapter ' theo sau là một hoặc nhiều kí tự số, tiếp đó là một dấu chấm . thập phân và một số lặp lại 0 hoặc nhiều lần. Biểu thức chính quy có cờ i nên không phân biệt chữ hoa và thường.

- -
var str = 'For more information, see Chapter 3.4.5.1';
-var re = /see (chapter \d+(\.\d)*)/i;
-var found = str.match(re);
-
-console.log(found);
-
-// logs [ 'see Chapter 3.4.5.1',
-//        'Chapter 3.4.5.1',
-//        '.1',
-//        index: 22,
-//        input: 'For more information, see Chapter 3.4.5.1' ]
-
-// 'see Chapter 3.4.5.1' là so khớp toàn bộ.
-// 'Chapter 3.4.5.1' được bắt bởi '(chapter \d+(\.\d)*)'.
-// '.1' là giá trị cuối cùng được bắt bởi '(\.\d)'.
-// Thuộc tính 'index' (22) là chỉ mục tính từ 0 của so khớp toàn bộ.
-// Thuộc tính 'input' là chuỗi gốc đã được phân tích ngữ pháp.
- -

Sử dụng cờ toàn cục và cờ không phân biệt chữ hoa/thường với match()

- -

Ví dụ dưới đây mô tả cách sử dụng cờ g và cờ i với match(). Tất cả chữ A tớ E và a tới e sẽ được trả lại và mỗi phần từ khớp nằm trong mảng.

- -
var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
-var regexp = /[A-E]/gi;
-var matches_array = str.match(regexp);
-
-console.log(matches_array);
-// ['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']
-
- -

Sử dụng match() không truyền tham số

- -
var str = "Nothing will come of nothing.";
-
-str.match();   //trả về [""]
- -

Một đối tượng không phải biểu thức chính quy được coi như một tham số

- -

Khi tham số là một chuỗi hoặc một số, ngầm định, nó được chuyển đổi thành một {{jsxref("RegExp")}} sử dụng new RegExp(obj). Nếu nó là một số dương với một dấu dương, phương thức Regexp() sẽ bỏ qua dấu dương.

- -
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" là một chuỗi. Trả về ["number"]
-str1.match(NaN);        // kiểu của NaN là kiểu number. Trả về ["NaN"]
-str1.match(Infinity);   // kiểu của Infinity là number. Trả về ["Infinity"]
-str1.match(+Infinity);  // Trả về ["Infinity"]
-str1.match(-Infinity);  // Trả về ["-Infinity"]
-str2.match(65);         // Trả về ["65"]
-str2.match(+65);        // Một số với dấu dương. Trả về ["65"]
-str3.match(null);       // Trả về ["null"]
- -

Thông số

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Thông sốTrạng tháiBình luận
{{SpecName('ES3')}}{{Spec2('ES3')}} -

Định nghĩa ban đầu. Được bổ sung trong JavaScript 1.2.

-
{{SpecName('ES5.1', '#sec-15.5.4.10', 'String.prototype.match')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.match', 'String.prototype.match')}}{{Spec2('ES6')}} 
{{SpecName('ESDraft', '#sec-string.prototype.match', 'String.prototype.match')}}{{Spec2('ESDraft')}} 
- -

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

- - - -

{{Compat("javascript.builtins.String.match")}}

- -

Lưu ý cho Firefox

- - - -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/string/normalize/index.html b/files/vi/web/javascript/reference/global_objects/string/normalize/index.html deleted file mode 100644 index faf26687eb..0000000000 --- a/files/vi/web/javascript/reference/global_objects/string/normalize/index.html +++ /dev/null @@ -1,146 +0,0 @@ ---- -title: String.prototype.normalize() -slug: Web/JavaScript/Reference/Global_Objects/String/normalize -tags: - - Chuỗi - - ECMAScript 2015 - - JavaScript - - Phương Thức - - Prototype - - String - - Tham khảo - - Unicode -translation_of: Web/JavaScript/Reference/Global_Objects/String/normalize ---- -
{{JSRef}}
- -

Phương thức normalize() trả về chuỗi với các ký tự Unicode đã được bình thường hóa (nếu giá trị truyền vào không phải chuỗi, nó sẽ được chuyển thành chuỗi trước).

- -
{{EmbedInteractiveExample("pages/js/string-normalize.html")}}
- - - -

Cú pháp

- -
str.normalize([form])
- -

Tham số

- -
-
form
-
Là một trong các giá trị "NFC", "NFD", "NFKC", hoặc "NFKD", để chỉ định định dạng Unicode của chuỗi ký tự. Nếu bỏ qua hoặc mang giá trị {{jsxref("undefined")}}, "NFC" sẽ được sử dụng. -
    -
  • NFC — Normalization Form Canonical Composition. (Unicode Dựng Sẵn)
  • -
  • NFD — Normalization Form Canonical Decomposition. (Unicode Tổ Hợp)
  • -
  • NFKC — Normalization Form Compatibility Composition. (Unicode Dựng Sẵn Tương Thích)
  • -
  • NFKD — Normalization Form Compatibility Decomposition. (Unicode Tổ Hợp Tương Thích)
  • -
-
-
- -

Giá trị trả về

- -

Một chuỗi mới với các ký tự Unicode đã được bình thường hóa.

- -

Lỗi có thể gây ra

- -
-
{{jsxref("RangeError")}}
-
Phương thức sẽ gây ra lỗi {{jsxref("RangeError")}} nếu như giá trị tham số form không phải là một trong các giá trị liệt kê ở trên.
-
- -

Mô tả

- -

Phương thức normalize() sẽ trả về một chuỗi mới với các ký tự Unicode đã được bình thường hóa theo một trong các định dạng Unicode Normalization Form. Nó không làm thay đổi chuỗi ban đầu.

- -
-

Đối với tiếng Việt, việc bình thường hóa giữa hai định dạng Canonical hoặc Compatibility (cùng Tổ Hợp hoặc Dựng Sẵn) là như nhau.

-
- -

Ví dụ

- -

Sử dụng normalize()

- -
// Chuỗi ban đầu
-
-// U+1E9B: LATIN SMALL LETTER LONG S WITH DOT ABOVE
-// U+0323: COMBINING DOT BELOW
-var str = '\u1E9B\u0323';
-
-
-// Canonically-composed form (NFC)
-
-// U+1E9B: LATIN SMALL LETTER LONG S WITH DOT ABOVE
-// U+0323: COMBINING DOT BELOW
-str.normalize('NFC'); // '\u1E9B\u0323'
-str.normalize();      // như trên
-
-
-// Canonically-decomposed form (NFD)
-
-// U+017F: LATIN SMALL LETTER LONG S
-// U+0323: COMBINING DOT BELOW
-// U+0307: COMBINING DOT ABOVE
-str.normalize('NFD'); // '\u017F\u0323\u0307'
-
-
-// Compatibly-composed (NFKC)
-
-// U+1E69: LATIN SMALL LETTER S WITH DOT BELOW AND DOT ABOVE
-str.normalize('NFKC'); // '\u1E69'
-
-
-// Compatibly-decomposed (NFKD)
-
-// U+0073: LATIN SMALL LETTER S
-// U+0323: COMBINING DOT BELOW
-// U+0307: COMBINING DOT ABOVE
-str.normalize('NFKD'); // '\u0073\u0323\u0307'
-
-// So sánh chuỗi tiếng Việt:
-
-// Unicode Dựng Sẵn
-var tvds = 'Tiếng Việt';
-// Unicode Tổ Hợp
-var tvth = 'Tiếng Việt';
-
-console.log(tvds.length); // 10
-console.log(tvth.length); // 14
-console.log(tvds == tvth); // false
-console.log(tvds.normalize('NFC') == tvth.normalize('NFC')); // true
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiGhi chú
{{SpecName('ES2015', '#sec-string.prototype.normalize', 'String.prototype.normalize')}}{{Spec2('ES2015')}}Định nghĩa lần đầu.
{{SpecName('ESDraft', '#sec-string.prototype.normalize', 'String.prototype.normalize')}}{{Spec2('ESDraft')}} 
- -

Trình duyệt hỗ trợ

- - - -

{{Compat("javascript.builtins.String.normalize")}}

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/string/repeat/index.html b/files/vi/web/javascript/reference/global_objects/string/repeat/index.html deleted file mode 100644 index 72e2179cf1..0000000000 --- a/files/vi/web/javascript/reference/global_objects/string/repeat/index.html +++ /dev/null @@ -1,118 +0,0 @@ ---- -title: String.prototype.repeat() -slug: Web/JavaScript/Reference/Global_Objects/String/repeat -tags: - - Chuỗi - - ES6 - - Phương Thức - - Tham khảo -translation_of: Web/JavaScript/Reference/Global_Objects/String/repeat ---- -
{{JSRef}}
- -

Phương thức repeat() xây dựng và trả về một chuỗi mới chứa số lượng nhất định bản sao chép của chuỗi được gọi tới và nối chung với nhau.

- -

Cú pháp

- -
str.repeat(count);
-
- -

Tham số

- -
-
count
-
Là 0 hoặc số nguyên dương, tức là giá trị nằm trong khoảng: [0, +∞), xác định số lần lặp để tạo chuỗi mới.
-
- -

Giá trị trả về

- -

Một chuỗi mới chứa số lần sao chép (count) chuỗi đầu vào.

- -

Ngoại lệ

- - - -

Ví dụ

- -
'abc'.repeat(-1);   // RangeError
-'abc'.repeat(0);    // ''
-'abc'.repeat(1);    // 'abc'
-'abc'.repeat(2);    // 'abcabc'
-'abc'.repeat(3.5);  // 'abcabcabc' (tham số đếm sẽ được chuyển thành số nguyên)
-'abc'.repeat(1/0);  // RangeError
-
-({ toString: () => 'abc', repeat: String.prototype.repeat }).repeat(2);
-// 'abcabc' (repeat() is a generic method)
-
- -

Polyfill

- -

Phương thức này đã được thêm vào kỹ thuật ES6 và có thể chưa có sẵn trong tất cả các bản bổ sung JS. Tuy nhiên bạn có thể sử dụng polyfill String.prototype.repeat() với snippet dưới đây:

- -
if (!String.prototype.repeat) {
-  String.prototype.repeat = function(count) {
-    'use strict';
-    if (this == null) {
-      throw new TypeError('can\'t convert ' + this + ' to object');
-    }
-    var str = '' + this;
-    count = +count;
-    if (count != count) {
-      count = 0;
-    }
-    if (count < 0) {
-      throw new RangeError('repeat count must be non-negative');
-    }
-    if (count == Infinity) {
-      throw new RangeError('repeat count must be less than infinity');
-    }
-    count = Math.floor(count);
-    if (str.length == 0 || count == 0) {
-      return '';
-    }
-
-    // Đảm bảo tham số đếm là số nguyên 31 bít cho phép ta tối ưu hóa nhiều
-    // phần chính. Nhưng dù sao thì, hầu hết các trình duyệt hiện tại (tháng Tám năm 2014) không thể xử lý
-    // các chuỗi 1 << 28 chars hoặc lớn hơn, vậy nên:
-    if (str.length * count >= 1 << 28) {
-      throw new RangeError('repeat count must not overflow maximum string size');
-    }
-    var rpt = '';
-    for (var i = 0; i < count; i++) {
-      rpt += str;
-    }
-    return rpt;
-  }
-}
-
- -

Thông số

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-string.prototype.repeat', 'String.prototype.repeat')}}{{Spec2('ES2015')}}Định nghĩa bổ sung.
{{SpecName('ESDraft', '#sec-string.prototype.repeat', 'String.prototype.repeat')}}{{Spec2('ESDraft')}} 
- -

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

- - - -

{{Compat("javascript.builtins.String.repeat")}}

diff --git a/files/vi/web/javascript/reference/global_objects/string/replace/index.html b/files/vi/web/javascript/reference/global_objects/string/replace/index.html deleted file mode 100644 index b9d5330c6c..0000000000 --- a/files/vi/web/javascript/reference/global_objects/string/replace/index.html +++ /dev/null @@ -1,233 +0,0 @@ ---- -title: String.prototype.replace() -slug: Web/JavaScript/Reference/Global_Objects/String/replace -translation_of: Web/JavaScript/Reference/Global_Objects/String/replace ---- -
{{JSRef}}
- -

Phương thức replace() sẽ trả về một chuỗi mới với một vài (hoặc tất cả) phần tử trùng khớp với pattern được thay thế bằng replacement. Pattern có thể là một chuỗi, hoặc một {{jsxref("RegExp")}}, và replacement có thể là một chuỗi, hoặc một function được gọi áp dụng cho mỗi kết quả trùng khớp. Nếu pattern là một chuỗi, thì phương thức replace() chỉ trả về kết quả đầu tiên trùng khớp.

- -

Replace() không làm thay đổi chuỗi gốc.

- -
{{EmbedInteractiveExample("pages/js/string-replace.html")}}
- - - -

Cú pháp

- -
const newStr = str.replace(regexp|substr, newSubstr|function)
- -

Parameters

- -
-
regexp (pattern)
-
Một {{jsxref("RegExp")}} object hoặc biểu thức RegEx. Phần tử được match sẽ được thay thế bởi newSubstr hoặc giá trị trả về bởi function.
-
substr
-
Một {{jsxref("String")}} cái mà sẽ bị thay thế bởi newSubstr. String này sẽ được xem như là một literal string và không phải là một regular expression. Nên chỉ có phần tử trùng khớp đầu tiên sẽ bị thay thế.
-
newSubstr (replacement)
-
Một {{jsxref("String")}} có nhiệm vụ thay thế substr được chỉ định trong regexp hoặc substr. Có nhiều kiểu thay thế khác nhau, xem chi tiết tại phần "Specifying a string as a parameter" bên dưới.
-
function (replacement)
-
Function được định nghĩa và gọi để sử dụng cho việc thay thế các phần tử trùng khớp với regexp hoặc substr. Đối số của function này có thể là các loại sau, xem chi tiết tại phần: "Specifying a function as a parameter" bên dưới.
-
- -

Return value

- -

Một string mới, với một số phần tử trùng khớp (hoặc tất cả phần tử trùng khớp) đã bị thay thế bởi các replacement.

- -

Mô tả

- -

Phương thức này không làm thay đổi {{jsxref("String")}} gốc. Nó chỉ đơn giản tạo ra một string mới.

- -

Để thực hiện tìm kiếm global search và replace, hãy thêm từ khóa g và biểu thức regular expression.

- -

Specifying a string as a parameter

- -

The replacement string can include the following special replacement patterns:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PatternInserts
$$Inserts a "$".
$&Inserts the matched substring.
$`Inserts the portion of the string that precedes the matched substring.
$'Inserts the portion of the string that follows the matched substring.
$nWhere n is a positive integer less than 100, inserts the nth parenthesized submatch string, provided the first argument was a {{jsxref("RegExp")}} object. Note that this is 1-indexed.
- -

Specifying a function as a parameter

- -

You can specify a function as the second parameter. In this case, the function will be invoked after the match has been performed. The function's result (return value) will be used as the replacement string. (Note: The above-mentioned special replacement patterns do not apply in this case.)

- -

Note that the function will be invoked multiple times for each full match to be replaced if the regular expression in the first parameter is global.

- -

The arguments to the function are as follows:

- - - - - - - - - - - - - - - - - - - - - - - - - - -
Possible nameSupplied value
matchThe matched substring. (Corresponds to $& above.)
p1, p2, ...The nth string found by a parenthesized capture group, provided the first argument to replace() was a {{jsxref("RegExp")}} object. (Corresponds to $1, $2, etc. above.) For example, if /(\a+)(\b+)/, was given, p1 is the match for \a+, and p2 for \b+.
offsetThe offset of the matched substring within the whole string being examined. (For example, if the whole string was 'abcd', and the matched substring was 'bc', then this argument will be 1.)
stringThe whole string being examined.
- -

(The exact number of arguments depends on whether the first argument is a {{jsxref("RegExp")}} object—and, if so, how many parenthesized submatches it specifies.)

- -

The following example will set newString to 'abc - 12345 - #$*%':

- -
function replacer(match, p1, p2, p3, offset, string) {
-  // p1 is nondigits, p2 digits, and p3 non-alphanumerics
-  return [p1, p2, p3].join(' - ');
-}
-let newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
-console.log(newString);  // abc - 12345 - #$*%
-
- -

Ví dụ

- -

Định nghĩa một biểu thức regular expression trong phương thức replace()

- -

Ví dụ bên dưới, regular expression được định nghĩa trong replace() và nó có thêm flat "i" (giúp kết quả matching không phân biệt chữ hoa và chữ thường).

- -
let str = 'Twas the night before Xmas...';
-let newstr = str.replace(/xmas/i, 'Christmas');
-console.log(newstr);  // Twas the night before Christmas...
-
- -

This logs 'Twas the night before Christmas...'.

- -
-

Note: See this guide for more explanations about regular expressions.

-
- -

Sử dụng flag global và flag ignore trong replace()

- -

Global replace (thay thế tất cả kết quả trùng khớp) có thể được thực hiện trong regex. Ví dụ sau, biểu thức regex có chứa các flag  global and ignore case flags cho phép replace() sẽ thay thế mỗi string 'apples' trong chuỗi gốc với string 'oranges'

- -
let re = /apples/gi;
-let str = 'Apples are round, and apples are juicy.';
-let newstr = str.replace(re, 'oranges');
-console.log(newstr);  // oranges are round, and oranges are juicy.
-
- -

This logs 'oranges are round, and oranges are juicy'.

- -

Đảo ngược vị trí của 2 từ trong một string

- -

Đoạn code bên dưới sẽ đảo qua lại vị trí của các từ trong một string. Ở phần replacement, đoạn code sử dụng capturing groups và ký tự $1,$2 để làm pattern cho phần replacement.

- -
let re = /(\w+)\s(\w+)/;
-let str = 'John Smith';
-let newstr = str.replace(re, '$2, $1');
-console.log(newstr);  // Smith, John
-
- -

This logs 'Smith, John'.

- -

Sử dụng một inline function để thay đổi các giá trị matched

- -

Trong ví dụ này, tất cả trường hợp chữ cái viết hoa trong một string sẽ được convert sang dạng viết thường, và dấu gạch ngang sẽ được thêm vào trước vị trí matching đó. Điều quan trọng ở đây, là cần thêm vào các dấu gạch ngang này trước khi trả về một replacement hoàn chỉnh để sử dụng.

- -

Replacement function này sẽ nhận vào các đoạn trích mà đã match với pattern làm tham số, và sử dụng các đoạn trích đó để biến đổi chữ hoa chữ thường, và ghép nối một dấu gạch ngang vào trước mỗi đoạn trích.

- -
function styleHyphenFormat(propertyName) {
-  function upperToHyphenLower(match, offset, string) {
-    return (offset > 0 ? '-' : '') + match.toLowerCase();
-  }
-  return propertyName.replace(/[A-Z]/g, upperToHyphenLower);
-}
-
- -

Given styleHyphenFormat('borderTop'), this returns 'border-top'.

- -

Because we want to further transform the result of the match before the final substitution is made, we must use a function. This forces the evaluation of the match prior to the {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}} method. If we had tried to do this using the match without a function, the {{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}} would have no effect.

- -
let newString = propertyName.replace(/[A-Z]/g, '-' + '$&'.toLowerCase());  // won't work
-
- -

This is because '$&'.toLowerCase() would first be evaluated as a string literal (resulting in the same '$&') before using the characters as a pattern.

- -

Replacing a Fahrenheit degree with its Celsius equivalent

- -

The following example replaces a Fahrenheit degree with its equivalent Celsius degree. The Fahrenheit degree should be a number ending with "F". The function returns the Celsius number ending with "C". For example, if the input number is "212F", the function returns "100C". If the number is "0F", the function returns "-17.77777777777778C".

- -

The regular expression test checks for any number that ends with F. The number of Fahrenheit degree is accessible to the function through its second parameter, p1. The function sets the Celsius number based on the Fahrenheit degree passed in a string to the f2c() function. f2c() then returns the Celsius number. This function approximates Perl's s///e flag.

- -
function f2c(x) {
-  function convert(str, p1, offset, s) {
-    return ((p1 - 32) * 5/9) + 'C';
-  }
-  let s = String(x);
-  let test = /(-?\d+(?:\.\d*)?)F\b/g;
-  return s.replace(test, convert);
-}
-
- -

Specifications

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-string.prototype.replace', 'String.prototype.replace')}}
- -

Browser compatibility

- - - -

{{Compat("javascript.builtins.String.replace")}}

- -

See also

- - diff --git a/files/vi/web/javascript/reference/global_objects/string/slice/index.html b/files/vi/web/javascript/reference/global_objects/string/slice/index.html deleted file mode 100644 index 002f1be65f..0000000000 --- a/files/vi/web/javascript/reference/global_objects/string/slice/index.html +++ /dev/null @@ -1,138 +0,0 @@ ---- -title: String.prototype.slice() -slug: Web/JavaScript/Reference/Global_Objects/String/slice -translation_of: Web/JavaScript/Reference/Global_Objects/String/slice ---- -
{{JSRef}}
- -

Phương thức slice() tạo ra một Chuỗi mới từ một phần của Chuỗi hiện tại.

- -

Cú pháp

- -
str.slice(beginSlice[, endSlice])
- -

Các tham số

- -
-
beginSlice
-
Chỉ số điểm bắt đầu của chuỗi con muốn lấy - bắt đầu từ 0. Nếu tham số này là số âm, thì nó tương đương với việc bạn gán nó bằng "độ dài chuỗi" + beginSlice. Ví dụ nếu beginSlice bằng -3 thì tương đương với beginSlice bằng "đội dài chuỗi" - 3.
-
endSlice
-
Tham số này không bắt buộc. Nếu có nó sẽ chỉ điểm cuối của chuỗi con muốn lấy. Nếu tham số này âm, nó sẽ được hiểu bằng "đội dài chuỗi" + endSlice. Ví dụ endSlice bằng -3 nó sẽ tương đương với "độ dài chuỗi" - 3
-
- -

Mô tả

- -

slice() thực hiện lấy một phần chuỗi từ chuỗi ban đầu và trả về một chuỗi mới. Chuỗi ban đầu sẽ không bị thay đổi giá trị.

- -

slice() sẽ lấy một phần chuỗi nhưng sẽ không chứa ký tự có chỉ số bằng với tham số endSlice. str.slice(1, 4) sẽ chỉ lấy ba ký tự 1,2 và 3.

- -

Ví dụ khác, str.slice(2, -1) sẽ lấy từ ký tự thứ 3 đến ký tự gần cuối, ký tự cuối không được đưa vào chuỗi mới

- -

Ví dụ

- -

Dùng slice() để tạo chuỗi mới

- -

Ví dụ sau sử dụng slice() để tạo chuỗi mới.

- -
var str1 = 'The morning is upon us.';
-var str2 = str1.slice(4, -2);
-
-console.log(str2); // OUTPUT: morning is upon u
-
- -

Dùng slice() với chỉ số âm

- -

Ví dụ sau sử dụng slice() với chỉ số âm.

- -
var str = 'The morning is upon us.';
-str.slice(-3);     // returns 'us.'
-str.slice(-3, -1); // returns 'us'
-str.slice(0, -1);  // returns 'The morning is upon us'
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tạTrạng tháiGhi chú
{{SpecName('ES3')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.2.
{{SpecName('ES5.1', '#sec-15.5.4.13', 'String.prototype.slice')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-string.prototype.slice', 'String.prototype.slice')}}{{Spec2('ES6')}} 
- -

Khả năng hỗ trợ của các trình duyệt

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
Tính năngChromeFirefox (Gecko)Internet ExplorerOperaSafari
Hỗ trợ cơ bản{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
Tính năngAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Hỗ trợ cơ bản{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/string/startswith/index.html b/files/vi/web/javascript/reference/global_objects/string/startswith/index.html deleted file mode 100644 index 7d3f6bfaa6..0000000000 --- a/files/vi/web/javascript/reference/global_objects/string/startswith/index.html +++ /dev/null @@ -1,128 +0,0 @@ ---- -title: String.prototype.startsWith() -slug: Web/JavaScript/Reference/Global_Objects/String/startsWith -translation_of: Web/JavaScript/Reference/Global_Objects/String/startsWith ---- -
{{JSRef}}
- -

startsWith() method xác định liệu một chuỗi bắt đầu với các chữ cái của chuỗi khác hay không, trả về giá trị true hoặc false tương ứng.

- -

Cú pháp

- -
str.startsWith(searchString[, position])
- -

Tham số

- -
-
searchString
-
Các ký tự cần tìm kiếm tại vị trí bắt đầu của chuỗi này.
-
position
-
Tùy chọn. Vị trí trong chuỗi bắt đầu tìm kiếm cho searchString; mặc định là 0.
-
- -

Miêu tả

- -

Method này cho phép bạn xác định liệu một chuỗi có bắt đầu với chuỗi khác không.

- -

Ví dụ

- -

Cách sử dụng startsWith()

- -
var str = 'To be, or not to be, that is the question.';
-
-console.log(str.startsWith('To be'));         // true
-console.log(str.startsWith('not to be'));     // false
-console.log(str.startsWith('not to be', 10)); // true
-
- -

Polyfill

- -

Method này đã được thêm vào chỉ dẫn kỹ thuật ECMAScript 6 và có thể chưa có sẵn trong tất cả JavaScript implementations. Tuy nhiên, bạn có thể polyfill String.prototype.startWith() với snippet sau:

- -
if (!String.prototype.startsWith) {
-  String.prototype.startsWith = function(searchString, position) {
-    position = position || 0;
-    return this.indexOf(searchString, position) === position;
-  };
-}
-
- -

Polyfill mạnh và được tối ưu hơn có sẵn trên GitHub bởi Mathias Bynens.

- -

Hướng dẫn kỹ thuật

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-string.prototype.startswith', 'String.prototype.startsWith')}}{{Spec2('ES6')}}Initial definition.
- -

Khả năng tương thích với Browser

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatChrome("41")}}{{CompatGeckoDesktop("17")}}{{CompatNo}}{{CompatChrome("41")}}{{CompatSafari("9")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatChrome("36")}}{{CompatGeckoMobile("17")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/global_objects/string/substr/index.html b/files/vi/web/javascript/reference/global_objects/string/substr/index.html deleted file mode 100644 index c7d477fede..0000000000 --- a/files/vi/web/javascript/reference/global_objects/string/substr/index.html +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: String.prototype.substr() -slug: Web/JavaScript/Reference/Global_Objects/String/substr -translation_of: Web/JavaScript/Reference/Global_Objects/String/substr ---- -
{{JSRef}}
- -
Phương thức substr()trả  về những ký tự trong một chuỗi được xác định bởi vị trí ký tự bắt đầu và số lượng ký tự theo sau đó.
- -

Cú pháp

- -
str.substr(start, [length])
- -

Các tham số

- -
-
start (bắt đầu)
-
Vị trí chính xác của ký tự bắt đầu. Nếu là một số âm, nó sẽ được xử lý như sau strLength - start trong đó strLengthlà chiều dài của chuỗi. Ví dụ, str.substr(-3) sẽ được coi như là str.substr(str.length -3)
-
length (độ dài)
-
Số lượng ký tự muốn lấy ra. Nếu tham số này là {{jsxref("undefined")}}, tất cả các ký tự từ vị trí bắt đầu tới kết thúc của chuỗi sẽ được lấy.
-
- -

Giá trị trả về

- -

Một chuỗi mới là phần đã lấy ra từ chuỗi ban đầu. Nếu  length là 0 hoặc là một số âm thì trả về một chuỗi rỗng.

- -

Mô tả

- -

start là chỉ số của ký tự. Chỉ số của ký tự đầu tiên là 0, và chỉ số của ký tự cuối cùng thì nhỏ hơn độ dài của chuỗi là 1. substr() bắt đầu lấy các ký tự tại start  và thu thập length các ký tự( trừ khi nó chấm tới cuối chuỗi trước, trong trường hợp này nó sẽ trả về ít hơn).

- -

Nếu start là số dương và lớn hơn hoặc bằng chiều dài của chuỗi, substr() trả về một chuỗi rỗng.

- -

Nếu start là số âm, substr() coi nó như chỉ là chỉ số của ký tự tính từ cuối chuỗi; chỉ số của ký tự cuối cùng là -1. Nếu  start là số âm và abs(start) lớn hơn chiều dài của chuỗi,substr() coi 0 như là chỉ số bắt đầu.

- -

Chú ý: Việc xử lý giá trị âm của tham số start như ở trên không được Microsoft JScript hỗ trợ.

- -

Nếu length là 0 hoặc âm, substr() trả về một mảng rỗng. Nếu length bị bỏ sót, substr() lấy các ký tự cho tới cuối chuỗi.

- -

Ví dụ

- -

Sử dụng substr()

- -
var str = 'abcdefghij';
-
-console.log('(1, 2): '   + str.substr(1, 2));   // '(1, 2): bc'
-console.log('(-3, 2): '  + str.substr(-3, 2));  // '(-3, 2): hi'
-console.log('(-3): '     + str.substr(-3));     // '(-3): hij'
-console.log('(1): '      + str.substr(1));      // '(1): bcdefghij'
-console.log('(-20, 2): ' + str.substr(-20, 2)); // '(-20, 2): ab'
-console.log('(20, 2): '  + str.substr(20, 2));  // '(20, 2): '
-
- -

Polyfill

- -

Microsoft's JScript không hỗ trợ các giá trị âm cho chi số bắt đầu. Nếu bạn mong muốn sử dụng tính năng này, bạn có thể sử dụng đoạn code dưới đây để xử lý bug này:

- -
// only run when the substr() function is broken
-if ('ab'.substr(-1) != 'b') {
-  /**
-   *  Get the substring of a string
-   *  @param  {integer}  start   where to start the substring
-   *  @param  {integer}  length  how many characters to return
-   *  @return {string}
-   */
-  String.prototype.substr = function(substr) {
-    return function(start, length) {
-      // call the original method
-      return substr.call(this,
-      	// did we get a negative start, calculate how much it is from the beginning of the string
-        // adjust the start parameter for negative value
-        start < 0 ? this.length + start : start,
-        length)
-    }
-  }(String.prototype.substr);
-}
-
- -

Các quy cách

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Quy cáchTình trạngÝ kiến
{{SpecName('ES3')}}{{Spec2('ES3')}}Da dinh nghia trong phu luc B bang Tuong thich (bo sung thong tin). Ap dung trong JavaScript 1.0
{{SpecName('ES5.1', '#sec-B.2.3', 'String.prototype.substr')}}{{Spec2('ES5.1')}}Da dinh nghia trong phu luc B bang Tuong thich (bo sung thong tin). 
{{SpecName('ES6', '#sec-string.prototype.substr', 'String.prototype.substr')}}{{Spec2('ES6')}}Da dinh nghia trong phu luc B (quy chuan) cho cac tinh nang bo sung cua ECMAScript doi voi cac trinh duyet Web
{{SpecName('ESDraft', '#sec-string.prototype.substr', 'String.prototype.substr')}}{{Spec2('ESDraft')}}Da dinh nghia trong phu luc B (quy chuan) cho cac tinh nang bo sung cua ECMAScript doi voi cac trinh duyet Web
- -

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

- - - -

{{Compat("javascript.builtins.String.substr")}}

- -

Tương tự

- - diff --git a/files/vi/web/javascript/reference/global_objects/string/substring/index.html b/files/vi/web/javascript/reference/global_objects/string/substring/index.html deleted file mode 100644 index e53b920581..0000000000 --- a/files/vi/web/javascript/reference/global_objects/string/substring/index.html +++ /dev/null @@ -1,195 +0,0 @@ ---- -title: String.prototype.substring() -slug: Web/JavaScript/Reference/Global_Objects/String/substring -translation_of: Web/JavaScript/Reference/Global_Objects/String/substring ---- -
{{JSRef}}
- -

substring() phương thức trả về chuỗi con của 1 chuỗi bắt đầu từ vị trí bắt đầu đến vị trí kết thúc, hoặc đến cuối chuỗi nếu không có vị trí kết thúc

- -

Cú pháp

- -
str.substring(indexStart[, indexEnd])
- -

Parameters

- -
-
indexStart
-
Một số integer giữa 0 và một số nhỏ hơn độ dài chuỗi, xác định vị trí kí tự đầu tiên trong chuỗi gốc để đưa vào chuỗi con.
-
indexEnd
-
Không bắt buộc. Một số integer giữa 0 và độ dài chuỗi. Chuỗi con không bao gồm ký tự ở vị trí indexEnd.
-
- -

Return value

- -

Chuỗi con trả về là chuỗi nằm ở vị trí từ indexStart đến vị trí ( indexEnd - 1 )

- -

Description

- -

substring() lấy ký tự từ vị trí indexStart tới vị trí (nhưng không bao gồm) indexEnd. Đặc biệt:

- - - -

Nếu indexStart lớn hơn indexEnd, chúng se được đổi chỗ; ví dụ, str.substring(1, 0) == str.substring(0, 1).

- -

Examples

- -

Using substring()

- -

The following example uses substring() to display characters from the string 'Mozilla':

- -
var anyString = 'Mozilla';
-
-// Displays 'Moz'
-console.log(anyString.substring(0, 3));
-console.log(anyString.substring(3, 0));
-
-// Displays 'lla'
-console.log(anyString.substring(4, 7));
-console.log(anyString.substring(4));
-console.log(anyString.substring(7, 4));
-
-// Displays 'Mozill'
-console.log(anyString.substring(0, 6));
-
-// Displays 'Mozilla'
-console.log(anyString.substring(0, 7));
-console.log(anyString.substring(0, 10));
-
- -

Using substring() with length property

- -

The following example uses the substring() method and {{jsxref("String.length", "length")}} property to extract the last characters of a particular string. This method may be easier to remember, given that you don't need to know the starting and ending indices as you would in the above examples.

- -
// Displays 'illa' the last 4 characters
-var anyString = 'Mozilla';
-var anyString4 = anyString.substring(anyString.length - 4);
-console.log(anyString4);
-
-// Displays 'zilla' the last 5 characters
-var anyString = 'Mozilla';
-var anyString5 = anyString.substring(anyString.length - 5);
-console.log(anyString5);
-
- -

Replacing a substring within a string

- -

The following example replaces a substring within a string. It will replace both individual characters and substrings. The function call at the end of the example changes the string 'Brave New World' into 'Brave New Web'.

- -
// Replaces oldS with newS in the string fullS
-function replaceString(oldS, newS, fullS) {
-  for (var i = 0; i < fullS.length; ++i) {
-    if (fullS.substring(i, i + oldS.length) == oldS) {
-      fullS = fullS.substring(0, i) + newS + fullS.substring(i + oldS.length, fullS.length);
-    }
-  }
-  return fullS;
-}
-
-replaceString('World', 'Web', 'Brave New World');
-
- -

Note that this can result in an infinite loop if oldS is itself a substring of newS — for example, if you attempted to replace 'World' with 'OtherWorld' here. A better method for replacing strings is as follows:

- -
function replaceString(oldS, newS, fullS) {
-  return fullS.split(oldS).join(newS);
-}
-
- -

The code above serves as an example for substring operations. If you need to replace substrings, most of the time you will want to use {{jsxref("String.prototype.replace()")}}.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1')}}{{Spec2('ES1')}}Implemented in JavaScript 1.0.
{{SpecName('ES5.1', '#sec-15.5.4.15', 'String.prototype.substring')}}{{Spec2('ES5.1')}}
{{SpecName('ES6', '#sec-string.prototype.substring', 'String.prototype.substring')}}{{Spec2('ES6')}}
{{SpecName('ESDraft', '#sec-string.prototype.substring', 'String.prototype.substring')}}{{Spec2('ESDraft')}}
- -

Browser compatibility

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

See also

- - diff --git a/files/vi/web/javascript/reference/global_objects/weakmap/index.html b/files/vi/web/javascript/reference/global_objects/weakmap/index.html deleted file mode 100644 index bdc4c9d40a..0000000000 --- a/files/vi/web/javascript/reference/global_objects/weakmap/index.html +++ /dev/null @@ -1,138 +0,0 @@ ---- -title: WeakMap -slug: Web/JavaScript/Reference/Global_Objects/WeakMap -translation_of: Web/JavaScript/Reference/Global_Objects/WeakMap ---- -
{{JSRef}}
- -

Đối tượng WeakMap là bộ sưu tập của các cặp key/value với các key được tham chiếu yếu ớt. Các key phải là đối tượng và các value có thể là bất kỳ giá trị nào. 

- -

Bạn có thể tham khảo thêm về WeakMaps trong hướng dẫn WeakMap object (trong Keyed collections).

- -

Description

- -

Các key của WeakMap phải là kiểu Object. Primitive data types không được phép là key(ví dụ một {{jsxref("Symbol")}} không thể là key của WeakMap).

- -

Why WeakMap?

- -

Một map APIcó thể được triển khai trong JavaScript với 2 mảng (một cho các key, một cho các value) được chia sẽ bởi 4 API method. Thiết lập các phần tử trong map sẽ đẩy đồng thời một key và value vào cuối mỗi mảng. Kết quả là chỉ số của key và value sẽ tương ứng ở cả 2 mảng. Lấy value từ một map sẽ liên quan tới vòng lặp qua tất cả các key để tìm kiếm kết quả phù hợp, sau đó sử dụng chỉ số của kết quả đó để nhận được giá trị tương ứng từ mảng các value.

- -

Việc thực hiện như vậy sẽ có 2 sự bất tiện chính:

- -
    -
  1. Điều đầu tiên là thiết lập và tìm kiếm trong mảng có n phần tử, vì cả 2 hành động này đều phải lặp lại qua danh sách các key để tìm giá trị thích hợp.
  2. -
  3. Điều bất tiện thứ 2 là rò rỉ bộ nhớ bởi vì các mảng sẽ phải đảm bảo các tham chiếu tới mỗi key và mỗi value được duy trì vô thời hạn. Các tham chiếu này sẽ ngăn các key khỏi garbage collected, ngay cả khi không có một tham chiếu nào khác tới đối tượng. Điều này cũng ngăn các value tương ứng khỏi garbage collected.
  4. -
- -

Ngược lại, các WeakMap giữ các tham chiếu "yếu" tới key, điều này có nghĩa chúng không được bảo vệ khỏi garbage collection trong trường hợp không có tham chiếu nào tới key. Điều này cũng tương tự với value. WeakMaps có thể đặc biệt là cấu trúc hiệu quả khi cần ánh xạ các key tới các thông tin về key có giá trị chỉ khi key chưa được thu gom rác.

- -

Bởi vì các tham chiếu là yếu, các key của WeakMap key không thể đếm được. Không có phương thức nào để lấy được danh sách các key. Nếu có, danh sách key sẽ phụ thuộc vào trạng thái của garbage collection, đưa ra tính không xác định. Nếu bạn muốn lấy được danh sách của key, bạn phải sử dụng {{jsxref("Map")}}.

- -

Constructor

- -
-
WeakMap()
-
Creates new WeakMap objects.
-
- -

Instance methods

- -
-
{{jsxref("WeakMap.delete", "WeakMap.prototype.delete(key)")}}
-
Removes any value associated to the key. WeakMap.prototype.has(key) will return false afterwards.
-
{{jsxref("WeakMap.get", "WeakMap.prototype.get(key)")}}
-
Returns the value associated to the key, or undefined if there is none.
-
{{jsxref("WeakMap.has", "WeakMap.prototype.has(key)")}}
-
Returns a Boolean asserting whether a value has been associated to the key in the WeakMap object or not.
-
{{jsxref("WeakMap.set", "WeakMap.prototype.set(key, value)")}}
-
Sets the value for the key in the WeakMap object. Returns the WeakMap object.
-
- -

Examples

- -

Using WeakMap

- -
const wm1 = new WeakMap(),
-      wm2 = new WeakMap(),
-      wm3 = new WeakMap();
-const o1 = {},
-      o2 = function() {},
-      o3 = window;
-
-wm1.set(o1, 37);
-wm1.set(o2, 'azerty');
-wm2.set(o1, o2); // a value can be anything, including an object or a function
-wm2.set(o3, undefined);
-wm2.set(wm1, wm2); // keys and values can be any objects. Even WeakMaps!
-
-wm1.get(o2); // "azerty"
-wm2.get(o2); // undefined, because there is no key for o2 on wm2
-wm2.get(o3); // undefined, because that is the set value
-
-wm1.has(o2); // true
-wm2.has(o2); // false
-wm2.has(o3); // true (even if the value itself is 'undefined')
-
-wm3.set(o1, 37);
-wm3.get(o1); // 37
-
-wm1.has(o1); // true
-wm1.delete(o1);
-wm1.has(o1); // false
-
- -

Implementing a WeakMap-like class with a .clear() method

- -
class ClearableWeakMap {
-  constructor(init) {
-    this._wm = new WeakMap(init);
-  }
-  clear() {
-    this._wm = new WeakMap();
-  }
-  delete(k) {
-    return this._wm.delete(k);
-  }
-  get(k) {
-    return this._wm.get(k);
-  }
-  has(k) {
-    return this._wm.has(k);
-  }
-  set(k, v) {
-    this._wm.set(k, v);
-    return this;
-  }
-}
-
- -

Specifications

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-weakmap-objects', 'WeakMap')}}
- -

Browser compatibility

- - - -

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

- -

See also

- - diff --git a/files/vi/web/javascript/reference/index.html b/files/vi/web/javascript/reference/index.html deleted file mode 100644 index be6e0ebe3d..0000000000 --- a/files/vi/web/javascript/reference/index.html +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: JavaScript reference -slug: Web/JavaScript/Reference -tags: - - JavaScript - - NeedsTranslation - - TopicStub -translation_of: Web/JavaScript/Reference ---- -
{{JsSidebar}}
- -

This part of the JavaScript section on MDN serves as a repository of facts about the JavaScript language. Read more about this reference.

- -

Global Objects

- -

This chapter documents all the JavaScript standard built-in objects, along with their methods and properties.

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Global_Objects', 'Standard objects (by category)')}}
- -

Statements

- -

This chapter documents all the JavaScript statements and declarations.

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Statements', 'Statements_and_declarations_by_category')}}
- -

Expressions and operators

- -

This chapter documents all the JavaScript expressions and operators.

- -
{{page('/en-US/docs/Web/JavaScript/Reference/Operators', 'Expressions_and_operators_by_category')}}
- -

Functions

- -

This chapter documents how to work with JavaScript functions to develop your applications.

- - - -

Additional reference pages

- - diff --git a/files/vi/web/javascript/reference/iteration_protocols/index.html b/files/vi/web/javascript/reference/iteration_protocols/index.html deleted file mode 100644 index 2485382349..0000000000 --- a/files/vi/web/javascript/reference/iteration_protocols/index.html +++ /dev/null @@ -1,383 +0,0 @@ ---- -title: Iteration protocols -slug: Web/JavaScript/Reference/Iteration_protocols -translation_of: Web/JavaScript/Reference/Iteration_protocols ---- -
{{jsSidebar("More")}}
- -

Là một vài bổ sung cho ECMAScript 2015, Iteration protocols không phải là một tích hợp sẵn hay cú pháp mới mà là protocols. Các giao thức này có thể triển khai bởi bất kỳ đối tượng nào đơn giản bằng cách thực hiện theo một số quy ước.

- -

Có 2 giao thức: iterable protocol và iterator protocol.

- -

The iterable protocol

- -

Iterable protocol cho phép các đối tượng của JavaScript xác định hoặc tuỳ chỉnh hành vi lặp của chúng, chẳng hạn như giá trị nào sẽ được lặp trong vòng lặp {{jsxref("Statements/for...of", "for...of")}}. Một số kiểu tích hợp sẵn built-in iterables là hành vi lặp mặc định, chẳng hạn như {{jsxref("Array")}} hoặc {{jsxref("Map")}}, trong khi các kiểu khác (chẳng hạn {{jsxref("Object")}}) không có.

- -

Để có thể triển khai giao thức iterable, một đối tượng phải có phương thức @@iterator, điều này có nghĩa là một đối tượng (hoặc một trong các đối tượng trên prototype chain của đối tượng đó) phải có một thuộc tính @@iterator và thao tác với thuộc tính đó thông qua hằng số {{jsxref("Symbol.iterator")}}:

- - - - - - - - - - - - - - -
PropertyValue
[Symbol.iterator]Một hàm không có tham số đầu vào trả ra một đối tượng phù hợp với iterator protocol.
- -

Bất cứ khi nào một đối tượng thực hiện vòng lặp (chẳng hạn như sử dụng vòng lặp {{jsxref("Statements/for...of", "for...of")}}), phương thức @@iterator sẽ được gọi mà không có tham số đầu vào, và trả ra iterator được sử dụng để thu được giá trị được lặp.

- -

Lưu ý khi hàm không tham số đầu vào được gọi, nó sẽ được gọi như là một phương thức của iterable object. Do đó bên trong hàm, từ khoá this có thể được sử dụng để truy cập vào các thuộc tính của iterable object, để quyết định những gì được cung cấp trong quá trình lặp.

- -

Hàm này có thể là một hàm bình thường hoặc nó có thể là một generator function, do đó khi được gọi, một iterator object sẽ được trả về. Bên trong của generator function, mỗi giá trị trả về có thể cung cấp bằng cách sử dụng yield.

- -

The iterator protocol

- -

Ierator protocol định nghĩa một cách tiêu chuẩn để tạo ra một chuỗi các giá trị (hưu hạn hoặc vô hạn), và  có thể trả về 1 giá trị khi tất cả các giá trị đã được tạo.

- -

Một đối tượng là một iterator khi nó triển khai phương thức next() với ý nghĩa như sau:

- - - - - - - - - - - - - - -
PropertyValue
next() -

Một hàm không tham số đầu vào trả ra một đối tượng có ít nhất 2 thuộc tính sau: 

- -
-
done (boolean)
-
-

Có giá trị false nếu iterator có thể tạo ra giá trị tiếp theo trong chuỗi. (This is equivalent to not specifying the done property altogether.)

- -

Có giá trị true nếu iterator kết thúc chuỗi. Trong trường hợp này, value có thể tuỳ chọn giá trị trả về cho iterator.

-
-
value
-
Bất kỳ giá trị JavaScript nào được trả về bởi iterator. ?Có thể bỏ qua khi done là true.
-
- -

Phương thức next() phải luôn luôn trả về một đối tượng với các thuộc tính thích hợp bao gồm done và value. Nếu một giá trị không phải đối tượng được trả về (chẳng hạn như false hoặc undefined), một {{jsxref("TypeError")}} ("iterator.next() returned a non-object value") sẽ được đẩy ra.

-
- -
-

Lưu ý: Không thể biết liệu một đối tượng cụ thể có triển khai giao thức iterator hay không. Tuy nhiên, dễ dàng để tạo ra một đối tượng mà có cả 2 giao thức iterator và iterable (như ví dụ dưới đây).

- -

Làm như vậy cho phép một iterator có thể sử dụng các cú pháp đa dạng của iterables. Vì vậy, rất hiếm khi triển khai giao thức Iterator Protocol mà không triển khai Iterable.

- -
// Satisfies both the Iterator Protocol and Iterable
-let myIterator = {
-    next: function() {
-        // ...
-    },
-    [Symbol.iterator]: function() { return this; }
-};
-
-
- -

Examples using the iteration protocols

- -

{{jsxref("String")}} là một ví dụ tích hợp sẵn iterable object:

- -
let someString = 'hi';
-console.log(typeof someString[Symbol.iterator]); // "function"
-
- -

{{jsxref("String/@@iterator", "iterator mặc định", "", 1)}} của String  trả ra lần lượt từng mã của các ký tự:

- -
let iterator = someString[Symbol.iterator]();
-console.log(iterator + ''); // "[object String Iterator]"
-
-console.log(iterator.next()); // { value: "h", done: false }
-console.log(iterator.next()); // { value: "i", done: false }
-console.log(iterator.next()); // { value: undefined, done: true }
- -

Some built-in constructs—such as the {{jsxref("Operators/Spread_operator", "spread syntax", "", 1)}}—use the same iteration protocol under the hood:

- -
console.log([...someString]); // ["h", "i"]
- -

You can redefine the iteration behavior by supplying our own @@iterator:

- -
// need to construct a String object explicitly to avoid auto-boxing
-let someString = new String('hi');
-
-someString[Symbol.iterator] = function () {
-  return {
-    // this is the iterator object, returning a single element (the string "bye")
-    next: function () {
-      return this._first ? {
-        value: 'bye',
-        done: (this._first = false)
-      } : {
-        done: true
-      }
-    },
-    _first: true
-  };
-};
-
- -

Notice how redefining @@iterator affects the behavior of built-in constructs that use the iteration protocol:

- -
console.log([...someString]); // ["bye"]
-console.log(someString + ''); // "hi"
-
- -

Iterable examples

- -

Built-in iterables

- -

{{jsxref("String")}}, {{jsxref("Array")}}, {{jsxref("TypedArray")}}, {{jsxref("Map")}}, and {{jsxref("Set")}} are all built-in iterables, because each of their prototype objects implements an @@iterator method.

- -

User-defined iterables

- -

You can make your own iterables like this:

- -
let myIterable = {};
-myIterable[Symbol.iterator] = function* () {
-    yield 1;
-    yield 2;
-    yield 3;
-};
-console.log([...myIterable]); // [1, 2, 3]
-
- -

Built-in APIs accepting iterables

- -

There are many APIs that accept iterables. Some examples include:

- - - -
new Map([[1, 'a'], [2, 'b'], [3, 'c']]).get(2); // "b"
-
-let myObj = {};
-
-new WeakMap([
-    [{}, 'a'],
-    [myObj, 'b'],
-    [{}, 'c']
-]).get(myObj);             // "b"
-
-new Set([1, 2, 3]).has(3); // true
-new Set('123').has('2');   // true
-
-new WeakSet(function* () {
-    yield {}
-    yield myObj
-    yield {}
-}()).has(myObj);           // true
-
- -

See Also

- - - -

Syntaxes expecting iterables

- -

Some statements and expressions expect iterables, for example the {{jsxref("Statements/for...of", "for...of")}} loops, the {{jsxref("Operators/Spread_syntax", "spread operator", "", 1)}})}}, {{jsxref("Operators/yield*", "yield*")}}, and {{jsxref("Operators/Destructuring_assignment", "destructuring assignment")}}:

- -
for (let value of ['a', 'b', 'c']) {
-    console.log(value);
-}
-// "a"
-// "b"
-// "c"
-
-console.log([...'abc']);   // ["a", "b", "c"]
-
-function* gen() {
-  yield* ['a', 'b', 'c'];
-}
-
-console.log(gen().next()); // { value: "a", done: false }
-
-[a, b, c] = new Set(['a', 'b', 'c']);
-console.log(a);            // "a"
-
-
- -

Non-well-formed iterables

- -

If an iterable's @@iterator method doesn't return an iterator object, then it's considered a non-well-formed iterable.

- -

Using one is likely to result in runtime errors or buggy behavior:

- -
let nonWellFormedIterable = {};
-nonWellFormedIterable[Symbol.iterator] = () => 1;
-[...nonWellFormedIterable]; // TypeError: [] is not a function
-
- -

Iterator examples

- -

Simple iterator

- -
function makeIterator(array) {
-  let nextIndex = 0
-  return {
-    next: function() {
-      return nextIndex < array.length ? {
-        value: array[nextIndex++],
-        done: false
-      } : {
-        done: true
-      };
-    }
-  };
-}
-
-let it = makeIterator(['yo', 'ya']);
-
-console.log(it.next().value); // 'yo'
-console.log(it.next().value); // 'ya'
-console.log(it.next().done);  // true
-
- -

Infinite iterator

- -
function idMaker() {
-  let index = 0;
-  return {
-    next: function() {
-      return {
-        value: index++,
-        done: false
-      };
-    }
-  };
-}
-
-let it = idMaker();
-
-console.log(it.next().value); // '0'
-console.log(it.next().value); // '1'
-console.log(it.next().value); // '2'
-// ...
-
- -

With a generator

- -
function* makeSimpleGenerator(array) {
-  let nextIndex = 0;
-  while (nextIndex < array.length) {
-    yield array[nextIndex++];
-  }
-}
-
-let gen = makeSimpleGenerator(['yo', 'ya']);
-
-console.log(gen.next().value); // 'yo'
-console.log(gen.next().value); // 'ya'
-console.log(gen.next().done);  // true
-
-function* idMaker() {
-  let index = 0;
-  while (true) {
-    yield index++;
-  }
-}
-
-let gen = idMaker()
-
-console.log(gen.next().value); // '0'
-console.log(gen.next().value); // '1'
-console.log(gen.next().value); // '2'
-// ...
-
- -

With ES2015 class

- -
class SimpleClass {
-  constructor(data) {
-    this.data = data;
-  }
-
-  [Symbol.iterator]() {
-    // Use a new index for each iterator. This makes multiple
-    // iterations over the iterable safe for non-trivial cases,
-    // such as use of break or nested looping over the same iterable.
-    let index = 0;
-
-    return {
-      next: () => {
-        if (index < this.data.length) {
-          return {value: this.data[index++], done: false}
-        } else {
-          return {done: true}
-        }
-      }
-    }
-  }
-}
-
-const simple = new SimpleClass([1,2,3,4,5]);
-
-for (const val of simple) {
-  console.log(val); // '1' '2' '3' '4' '5'
-}
-
- -

Is a generator object an iterator or an iterable?

- -

A {{jsxref("Generator", "generator object", "", 1)}} is both iterator and iterable:

- -
let aGeneratorObject = function* () {
-  yield 1;
-  yield 2;
-  yield 3;
-}();
-
-console.log(typeof aGeneratorObject.next);
-// "function", because it has a next method, so it's an iterator
-
-console.log(typeof aGeneratorObject[Symbol.iterator]);
-// "function", because it has an @@iterator method, so it's an iterable
-
-console.log(aGeneratorObject[Symbol.iterator]() === aGeneratorObject);
-// true, because its @@iterator method returns itself (an iterator), so it's an well-formed iterable
-
-console.log([...aGeneratorObject]);
-// [1, 2, 3]
-
- -

Specifications

- - - - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-iteration', 'Iteration')}}
- -

See also

- - diff --git a/files/vi/web/javascript/reference/operators/conditional_operator/index.html b/files/vi/web/javascript/reference/operators/conditional_operator/index.html deleted file mode 100644 index 62cc4cadb5..0000000000 --- a/files/vi/web/javascript/reference/operators/conditional_operator/index.html +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: Conditional (ternary) operator -slug: Web/JavaScript/Reference/Operators/Conditional_Operator -translation_of: Web/JavaScript/Reference/Operators/Conditional_Operator ---- -
{{jsSidebar("Operators")}}
- -

Toán tử điều kiện (ba ngôi) là toán tử duy nhất của JavaScript cần tới ba toán hạng. Toán tử này thường dùng tắt cho câu lệnh if.

- -
{{EmbedInteractiveExample("pages/js/expressions-conditionaloperators.html")}}
- - - -

Cú pháp

- -
condition ? exprT : exprF 
- -

Tham số

- -
-
condition
-
Biểu thức mà giá trị của nó được dùng như điều kiện.
-
- -
-
exprT, exprF
-
Biểu thức với giá trị có kiểu bất kỳ.
-
- -

Mô tả

- -

Nếu condition có thể chuyển đổi thànhtrue (hay là {{Glossary("truthy")}}), toán tử trả về giá trị của exprT; ngược lại (khi condition là {{Glossary("falsy")}}), nó trả về giá trị của exprF.

- -

(Trong cả hai trường hợp, biểu thức còn lại đều không được duyệt tới.)

- -

Ngoài false ra, các biểu thức falsy có thể xảy ra bao gồm: nullNaN0, xâu ký tự rỗng (""), và undefined. Nếu condition là một trong những gì vừa liệt kê phía trên, kết quả của biểu thức điều kiện sẽ là exprF.

- -

Ví dụ đơn giản:

- -
var age = 26;
-var beverage = (age >= 21) ? "Beer" : "Juice";
-console.log(beverage); // "Beer"
-
- -

Thường dùng để xử lý giá trị null:

- -
function greeting(person) {
-    var name = person ? person.name : "stranger";
-    return "Howdy, " + name;
-}
-
-console.log(greeting({name: 'Alice'}));  // "Howdy, Alice"
-console.log(greeting(null));             // "Howdy, stranger"​​​​​
-
- -

Điều kiện nối tiếp

- -

Toán tử điều kiện tuân theo suy dẫn phải, tức là nó có thể được gọi "nối tiếp" theo cách sau đây, tương tự như với if … else if … else if … else nối tiếp nhau:

- -
function example(…) {
-    return condition1 ? value1
-         : condition2 ? value2
-         : condition3 ? value3
-         : value4;
-}
-
-// Equivalent to:
-
-function example(…) {
-    if (condition1) { return value1; }
-    else if (condition2) { return value2; }
-    else if (condition3) { return value3; }
-    else { return value4; }
-}
-
- -

Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Đặc tảTrạng tháiBình luận
{{SpecName('ESDraft', '#sec-conditional-operator', 'Conditional Operator')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-conditional-operator', 'Conditional Operator')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.12', 'The conditional operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1', '#sec-11.12', 'The conditional operator')}}{{Spec2('ES1')}}Định nghĩa lần đầu. Cài đặt trong JavaScript 1.0.
- -

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

- - - -

{{Compat("javascript.operators.conditional")}}

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/operators/delete/index.html b/files/vi/web/javascript/reference/operators/delete/index.html deleted file mode 100644 index 46a837d094..0000000000 --- a/files/vi/web/javascript/reference/operators/delete/index.html +++ /dev/null @@ -1,292 +0,0 @@ ---- -title: delete operator -slug: Web/JavaScript/Reference/Operators/delete -translation_of: Web/JavaScript/Reference/Operators/delete ---- -
{{jsSidebar("Operators")}}
- -

Toán tử delete của JavaScript loại bỏ một thuộc tính khỏi object; nếu không tồn tại tham chiếu tới thuộc tính, nó sẽ tự động giải phóng.

- -
{{EmbedInteractiveExample("pages/js/expressions-deleteoperator.html")}}
- - - -

Cú pháp

- -
delete expression 
- -

với expression thực thi thành tham chiếu đến thuộc tính nào đó, tức là:

- -
delete object.property
-delete object['property']
-
- -

Tham số

- -
-
object
-
Tên object, hoặc biểu thức thực thi tới object.
-
property
-
Thuộc tính muốn xoá.
-
- -

Giá trị trả về

- -

true cho mọi trường hợp trừ khi thuộc tính là own non-configurable, trong trường hợp đó, trả về false trong chế độ non-strict.

- -

Ngoại lệ

- -

Quăng {{jsxref("TypeError")}} trong chế độ strict nếu thuộc tính là own non-configurable.

- -

Mô tả

- -

Khác với suy nghĩ của nhiều người, toán tử delete không trực tiếp giải phóng bộ nhớ. Quản lý bộ nhớ được thực hiện trung gian qua việc bẻ tham chiếu. Xem trang quản lý bộ nhớ để biết thêm chi tiết.

- -

Toán tử delete loại bỏ thuộc tính xác định trong object. Nếu xoá thành công, nó sẽ trả về true, ngoài ra thì false. Tuy nhiên, hãy lưu ý những kịch bản có thể xảy đến sau đây:

- - - -

Snippet sau đưa ra ví dụ đơn giản:

- -
var Employee = {
-  age: 28,
-  name: 'abc',
-  designation: 'developer'
-}
-
-console.log(delete Employee.name);   // trả về true
-console.log(delete Employee.age);    // trả về true
-
-// Khi cố xoá một thuộc tính không tồn tại
-// sẽ trả về giá trị true
-console.log(delete Employee.salary); // trả về true
-
- -

Thuộc tính không-thể-cấu-hình

- -

Khi một thuộc tính được đánh dấu không-thể-cấu-hình, delete không có tác dụng nào, và sẽ trả về false. Trong chế độ strict, lỗi TypeError sẽ nhảy ra.

- -
var Employee = {};
-Object.defineProperty(Employee, 'name', {configurable: false});
-
-console.log(delete Employee.name);  // trả về false
-
- -

{{jsxref("Statements/var","var")}}, {{jsxref("Statements/let","let")}} và {{jsxref("Statements/const","const")}} tạo ra thuộc tính không-thể-cấu-hình mà không thể xoá bằng toán tử delete:

- -
var nameOther = 'XYZ';
-
-// Ta có thể truy cập vào thuộc tính toàn cục này thông qua:
-Object.getOwnPropertyDescriptor(window, 'nameOther');
-
-// output: Object {value: "XYZ",
-//                  writable: true,
-//                  enumerable: true,
-//                  configurable: false}
-
-// Bởi vì "nameOther" được thêm vào nhờ dùng
-// từ khoá var, nên nó được đánh dấu là "không-thể-cấu-hình"
-
-delete nameOther;   // trả về false
- -

Trong chế độ strict, ngoại lệ sẽ quăng ra.

- -

Chế độ strict và non-strict

- -

Khi ở trong chế độ strict, nếu delete được dùng để tham chiếu trực tiếp tới một biến, một đối số của hàm hoặc tên hàm, nó sẽ quăng ra {{jsxref("SyntaxError")}}.

- -

Bất cứ biến nào được định nghĩa với var đều được đánh dấu là không-thể-cấu-hình. Trong ví dụ sau đây, salary là không-thể-cấu-hình và không thể xoá. Trong chế độ non-strict, phép toán delete sẽ trả về false.

- -
function Employee() {
-  delete salary;
-  var salary;
-}
-
-Employee();
-
- -

Cùng xem mã nguồn tương tự hoạt động ra sao trong chế độ strict nhé. Thay vì trả về false, SyntaxError được quăng ra.

- -
"use strict";
-
-function Employee() {
-  delete salary;  // SyntaxError
-  var salary;
-}
-
-// Tương tự, bất cứ truy nhập trực tiếp nào vào hàm
-// dùng delete đều quăng ra SyntaxError
-
-function DemoFunction() {
-  //vài đoạn code
-}
-
-delete DemoFunction; // SyntaxError
-
- -

Ví dụ

- -
// Tạo thuộc tính adminName trên phạm vi toàn cục.
-adminName = 'xyz';
-
-// Tạo thuộc tính empCount trên phạm vi toàn cục =.
-// Vì dùng var, thuộc tính này được đánh dấu là không-thể-cấu-hình.
-// Điều tương tự xảy đến với let và const.
-var empCount = 43;
-
-EmployeeDetails = {
-  name: 'xyz',
-  age: 5,
-  designation: 'Developer'
-};
-
-// adminName là thuộc tính trên phạm vi toàn cục.
-// Nó có thể bị xoá bởi được khởi tạo mà không dùng var,
-// và vì thế khả cấu.
-delete adminName;       // trả về true
-
-// Ngược lại, empCount không khả cấu
-// bởi dùng var.
-delete empCount;       // trả về false
-
-// Có thể dùng delete để loại bỏ thuộc tính khỏi object.
-delete EmployeeDetails.name; // trả về true
-
-// Thậm chí thuộc tính không tồn tại, delete vẫn trả về "true".
-delete EmployeeDetails.salary; // trả về true
-
-// delete không có tác dụng với thuộc tính dựng sẵn.
-delete Math.PI; // trả về false
-
-// EmployeeDetails là thuộc tính trong phạm vi toàn cục.
-// Vì được khởi tạo mà không dùng "var", nó được đánh dấu là khả cấu.
-delete EmployeeDetails;   // trả về true
-
-function f() {
-  var z = 44;
-
-  // delete không có tác dụng với tên biến cục bộ
-  delete z;     // trả về false
-}
-
- -

delete và prototype chain

- -

Trong ví dụ sau, ta sẽ xoá một thuộc tính riêng của object mà vẫn tồn tại thuộc tính cùng tên trong prototype chain:

- -
function Foo() {
-  this.bar = 10;
-}
-
-Foo.prototype.bar = 42;
-
-var foo = new Foo();
-
-// foo.bar liên kết với
-// thuộc tính riêng.
-console.log(foo.bar); // 10
-
-// Xoá thuộc tính riêng trên
-// foo object.
-delete foo.bar; // trả về true
-
-// foo.bar vẫn sẵn sàng trên
-// prototype chain.
-console.log(foo.bar); // 42
-
-// Xoá thuộc tính trên prototype.
-delete Foo.prototype.bar; // trả về true
-
-// Thuộc tính "bar" không còn có thể
-// kể thừa từ Foo bởi nó đã bị xoá
-console.log(foo.bar); // undefined
- -

Xoá phần tử mảng

- -

Khi bạn xoá phần tử mảng, độ dài mảng không bị ảnh hưởng. Thậm chí khi bạn xoá phần tử cuối của mảng cũng không thay đổi được điều này.

- -

Khi toán tử delete loại bỏ một phần tử mảng, phần tử đó không còn trong mảng. Trong ví dụ sau, trees[3] bị xoá bởi delete.

- -
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
-delete trees[3];
-if (3 in trees) {
-    // không thực thi đoạn code này
-}
- -

Nếu bạn muốn giữ lại phần tử mảng và gán giá trị undefined cho nó, hãy dùng undefined thay vì toán tử delete. Trong ví dụ sau, trees[3] được gán giá trị undefined, nhưng phần tử mảng vẫn tồn tại:

- -
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
-trees[3] = undefined;
-if (3 in trees) {
-    // đoạn code trong này sẽ chạy
-}
- -

Thay vì thế, nếu muốn loại bỏ phần tử mảng bằng cách thay đổi nội dung của mảng, hãy dùng phương thức {{jsxref("Array.splice", "splice")}}. Trong ví dụ sau, trees[3] bị xoá bỏ hoàn toàn khỏi mảng thông qua {{jsxref("Array.splice", "splice")}}:

- -
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
-trees.splice(3,1);
-console.log(trees); // ["redwood", "bay", "cedar", "maple"]
-
- -

Đặc Đặc tả

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-delete-operator', 'The delete Operator')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-delete-operator', 'The delete Operator')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-11.4.1', 'The delete Operator')}}{{Spec2('ES5.1')}} 
{{SpecName('ES1', '#sec-11.4.1', 'The delete Operator')}}{{Spec2('ES1')}}Định nghĩa lần đầu. Cài đặt trong JavaScript 1.2.
- -

Trình duyệt hỗ trợ

- - - -

{{Compat("javascript.operators.delete")}}

- -

Ghi chú Cross-browser

- -

Although ECMAScript makes iteration order of objects implementation-dependent, it may appear that all major browsers support an iteration order based on the earliest added property coming first (at least for properties not on the prototype). However, in the case of Internet Explorer, when one uses delete on a property, some confusing behavior results, preventing other browsers from using simple objects like object literals as ordered associative arrays. In Explorer, while the property value is indeed set to undefined, if one later adds back a property with the same name, the property will be iterated in its old position--not at the end of the iteration sequence as one might expect after having deleted the property and then added it back.

- -

If you want to use an ordered associative array in a cross-browser environment, use a {{jsxref("Map")}} object if available, or simulate this structure with two separate arrays (one for the keys and the other for the values), or build an array of single-property objects, etc.

- -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/operators/function/index.html b/files/vi/web/javascript/reference/operators/function/index.html deleted file mode 100644 index 1e302774be..0000000000 --- a/files/vi/web/javascript/reference/operators/function/index.html +++ /dev/null @@ -1,175 +0,0 @@ ---- -title: function expression -slug: Web/JavaScript/Reference/Operators/function -translation_of: Web/JavaScript/Reference/Operators/function ---- -
{{jsSidebar("Operators")}}
- -

Từ khóa function (hàm) có thể dùng để định nghĩa chức năng bên trong một biểu thức.

- -

Cú pháp

- -
var myFunction = function [name]([param1[, param2[, ..., paramN]]]) {
-   statements
-};
- -

Tham số

- -
-
name
-
Tên hàm. Có thể bỏ qua, trong trường hợp chức năng đó là vô danh. Nó mô tả chính xác nhiệm vụ mà hàm sẽ làm.
-
paramN
-
Tên các đối số truyền vào.
-
statements
-
Các câu lệnh xử lý các đối số paramN truyền vào.
-
- -

Mô tả

- -

Một biểu thức chức năng (function) is very similar to and has almost the same syntax as a function statement (see function statement for details). The main difference between a function expression and a function statement is the function name, which can be omitted in function expressions to create anonymous functions. A function expression can be used as a IIFE (Immediately Invoked Function Expression) which runs as soon as it is defined. See also the chapter about functions for more information.

- -

Function expression hoisting

- -

Function expressions in JavaScript are not hoisted, unlike {{jsxref("Statements/function", "function declarations", "#Function_declaration_hoisting")}}. You can't use function expressions before you define them:

- -
notHoisted(); // TypeError: notHoisted is not a function
-
-var notHoisted = function() {
-   console.log('bar');
-};
-
- -

Examples

- -

The following example defines an unnamed function and assigns it to x. The function returns the square of its argument:

- -
var x = function(y) {
-   return y * y;
-};
-
- -

Named function expression

- -

If you want to refer to the current function inside the function body, you need to create a named function expression. This name is then local only to the function body (scope). This also avoids using the non-standard arguments.callee property.

- -
var math = {
-  'factorial': function factorial(n) {
-    if (n <= 1)
-      return 1;
-    return n * factorial(n - 1);
-  }
-};
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ESDraft')}} 
{{SpecName('ES6', '#sec-function-definitions', 'Function definitions')}}{{Spec2('ES6')}} 
{{SpecName('ES5.1', '#sec-13', 'Function definition')}}{{Spec2('ES5.1')}} 
{{SpecName('ES3', '#sec-13', 'Function definition')}}{{Spec2('ES3')}}Initial definition. Implemented in JavaScript 1.5.
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Trailing comma in parameters{{CompatUnknown}}{{CompatGeckoDesktop("52.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Trailing comma in parameters{{CompatUnknown}}{{CompatUnknown}}{{CompatGeckoMobile("52.0")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

See also

- - diff --git a/files/vi/web/javascript/reference/operators/index.html b/files/vi/web/javascript/reference/operators/index.html deleted file mode 100644 index 139208dbca..0000000000 --- a/files/vi/web/javascript/reference/operators/index.html +++ /dev/null @@ -1,298 +0,0 @@ ---- -title: Expressions and operators -slug: Web/JavaScript/Reference/Operators -tags: - - JavaScript - - NeedsTranslation - - Operators - - TopicStub -translation_of: Web/JavaScript/Reference/Operators ---- -
{{jsSidebar("Operators")}}
- -

This chapter documents all the JavaScript language operators, expressions and keywords.

- -

Expressions and operators by category

- -

For an alphabetical listing see the sidebar on the left.

- -

Primary expressions

- -

Basic keywords and general expressions in JavaScript.

- -
-
{{jsxref("Operators/this", "this")}}
-
The this keyword refers to the function's execution context.
-
{{jsxref("Operators/function", "function")}}
-
The function keyword defines a function expression.
-
{{jsxref("Operators/class", "class")}}
-
The class keyword defines a class expression.
-
{{jsxref("Operators/function*", "function*")}}
-
The function* keyword defines a generator function expression.
-
{{jsxref("Operators/yield", "yield")}}
-
Pause and resume a generator function.
-
{{jsxref("Operators/yield*", "yield*")}}
-
Delegate to another generator function or iterable object.
-
{{jsxref("Global_Objects/Array", "[]")}}
-
Array initializer/literal syntax.
-
{{jsxref("Operators/Object_initializer", "{}")}}
-
Object initializer/literal syntax.
-
{{jsxref("Global_Objects/RegExp", "/ab+c/i")}}
-
Regular expression literal syntax.
-
{{jsxref("Operators/Grouping", "( )")}}
-
Grouping operator.
-
- -

Left-hand-side expressions

- -

Left values are the destination of an assignment.

- -
-
{{jsxref("Operators/Property_accessors", "Property accessors", "", 1)}}
-
Member operators provide access to a property or method of an object
- (object.property and object["property"]).
-
{{jsxref("Operators/new", "new")}}
-
The new operator creates an instance of a constructor.
-
new.target
-
In constructors, new.target refers to the constructor that was invoked by {{jsxref("Operators/new", "new")}}.
-
{{jsxref("Operators/super", "super")}}
-
The super keyword calls the parent constructor.
-
{{jsxref("Operators/Spread_operator", "...obj")}}
-
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
-
- -

Increment and decrement

- -

Postfix/prefix increment and postfix/prefix decrement operators.

- -
-
{{jsxref("Operators/Arithmetic_Operators", "A++", "#Increment")}}
-
Postfix increment operator.
-
{{jsxref("Operators/Arithmetic_Operators", "A--", "#Decrement")}}
-
Postfix decrement operator.
-
{{jsxref("Operators/Arithmetic_Operators", "++A", "#Increment")}}
-
Prefix increment operator.
-
{{jsxref("Operators/Arithmetic_Operators", "--A", "#Decrement")}}
-
Prefix decrement operator.
-
- -

Unary operators

- -

A unary operation is operation with only one operand.

- -
-
{{jsxref("Operators/delete", "delete")}}
-
The delete operator deletes a property from an object.
-
{{jsxref("Operators/void", "void")}}
-
The void operator discards an expression's return value.
-
{{jsxref("Operators/typeof", "typeof")}}
-
The typeof operator determines the type of a given object.
-
{{jsxref("Operators/Arithmetic_Operators", "+", "#Unary_plus")}}
-
The unary plus operator converts its operand to Number type.
-
{{jsxref("Operators/Arithmetic_Operators", "-", "#Unary_negation")}}
-
The unary negation operator converts its operand to Number type and then negates it.
-
{{jsxref("Operators/Bitwise_Operators", "~", "#Bitwise_NOT")}}
-
Bitwise NOT operator.
-
{{jsxref("Operators/Logical_Operators", "!", "#Logical_NOT")}}
-
Logical NOT operator.
-
- -

Arithmetic operators

- -

Arithmetic operators take numerical values (either literals or variables) as their operands and return a single numerical value.

- -
-
{{jsxref("Operators/Arithmetic_Operators", "+", "#Addition")}}
-
Addition operator.
-
{{jsxref("Operators/Arithmetic_Operators", "-", "#Subtraction")}}
-
Subtraction operator.
-
{{jsxref("Operators/Arithmetic_Operators", "/", "#Division")}}
-
Division operator.
-
{{jsxref("Operators/Arithmetic_Operators", "*", "#Multiplication")}}
-
Multiplication operator.
-
{{jsxref("Operators/Arithmetic_Operators", "%", "#Remainder")}}
-
Remainder operator.
-
- -
-
{{jsxref("Operators/Arithmetic_Operators", "**", "#Exponentiation")}}
-
Exponentiation operator.
-
- -

Relational operators

- -

A comparison operator compares its operands and returns a Boolean value based on whether the comparison is true.

- -
-
{{jsxref("Operators/in", "in")}}
-
The in operator determines whether an object has a given property.
-
{{jsxref("Operators/instanceof", "instanceof")}}
-
The instanceof operator determines whether an object is an instance of another object.
-
{{jsxref("Operators/Comparison_Operators", "<", "#Less_than_operator")}}
-
Less than operator.
-
{{jsxref("Operators/Comparison_Operators", ">", "#Greater_than_operator")}}
-
Greater than operator.
-
{{jsxref("Operators/Comparison_Operators", "<=", "#Less_than_or_equal_operator")}}
-
Less than or equal operator.
-
{{jsxref("Operators/Comparison_Operators", ">=", "#Greater_than_or_equal_operator")}}
-
Greater than or equal operator.
-
- -
-

Note: => is not an operator, but the notation for Arrow functions.

-
- -

Equality operators

- -

The result of evaluating an equality operator is always of type Boolean based on whether the comparison is true.

- -
-
{{jsxref("Operators/Comparison_Operators", "==", "#Equality")}}
-
Equality operator.
-
{{jsxref("Operators/Comparison_Operators", "!=", "#Inequality")}}
-
Inequality operator.
-
{{jsxref("Operators/Comparison_Operators", "===", "#Identity")}}
-
Identity operator.
-
{{jsxref("Operators/Comparison_Operators", "!==", "#Nonidentity")}}
-
Nonidentity operator.
-
- -

Bitwise shift operators

- -

Operations to shift all bits of the operand.

- -
-
{{jsxref("Operators/Bitwise_Operators", "<<", "#Left_shift")}}
-
Bitwise left shift operator.
-
{{jsxref("Operators/Bitwise_Operators", ">>", "#Right_shift")}}
-
Bitwise right shift operator.
-
{{jsxref("Operators/Bitwise_Operators", ">>>", "#Unsigned_right_shift")}}
-
Bitwise unsigned right shift operator.
-
- -

Binary bitwise operators

- -

Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.

- -
-
{{jsxref("Operators/Bitwise_Operators", "&", "#Bitwise_AND")}}
-
Bitwise AND.
-
{{jsxref("Operators/Bitwise_Operators", "|", "#Bitwise_OR")}}
-
Bitwise OR.
-
{{jsxref("Operators/Bitwise_Operators", "^", "#Bitwise_XOR")}}
-
Bitwise XOR.
-
- -

Binary logical operators

- -

Logical operators are typically used with boolean (logical) values, and when they are, they return a boolean value.

- -
-
{{jsxref("Operators/Logical_Operators", "&&", "#Logical_AND")}}
-
Logical AND.
-
{{jsxref("Operators/Logical_Operators", "||", "#Logical_OR")}}
-
Logical OR.
-
- -

Conditional (ternary) operator

- -
-
{{jsxref("Operators/Conditional_Operator", "(condition ? ifTrue : ifFalse)")}}
-
-

The conditional operator returns one of two values based on the logical value of the condition.

-
-
- -

Assignment operators

- -

An assignment operator assigns a value to its left operand based on the value of its right operand.

- -
-
{{jsxref("Operators/Assignment_Operators", "=", "#Assignment")}}
-
Assignment operator.
-
{{jsxref("Operators/Assignment_Operators", "*=", "#Multiplication_assignment")}}
-
Multiplication assignment.
-
{{jsxref("Operators/Assignment_Operators", "/=", "#Division_assignment")}}
-
Division assignment.
-
{{jsxref("Operators/Assignment_Operators", "%=", "#Remainder_assignment")}}
-
Remainder assignment.
-
{{jsxref("Operators/Assignment_Operators", "+=", "#Addition_assignment")}}
-
Addition assignment.
-
{{jsxref("Operators/Assignment_Operators", "-=", "#Subtraction_assignment")}}
-
Subtraction assignment
-
{{jsxref("Operators/Assignment_Operators", "<<=", "#Left_shift_assignment")}}
-
Left shift assignment.
-
{{jsxref("Operators/Assignment_Operators", ">>=", "#Right_shift_assignment")}}
-
Right shift assignment.
-
{{jsxref("Operators/Assignment_Operators", ">>>=", "#Unsigned_right_shift_assignment")}}
-
Unsigned right shift assignment.
-
{{jsxref("Operators/Assignment_Operators", "&=", "#Bitwise_AND_assignment")}}
-
Bitwise AND assignment.
-
{{jsxref("Operators/Assignment_Operators", "^=", "#Bitwise_XOR_assignment")}}
-
Bitwise XOR assignment.
-
{{jsxref("Operators/Assignment_Operators", "|=", "#Bitwise_OR_assignment")}}
-
Bitwise OR assignment.
-
{{jsxref("Operators/Destructuring_assignment", "[a, b] = [1, 2]")}}
- {{jsxref("Operators/Destructuring_assignment", "{a, b} = {a:1, b:2}")}}
-
-

Destructuring assignment allows you to assign the properties of an array or object to variables using syntax that looks similar to array or object literals.

-
-
- -

Comma operator

- -
-
{{jsxref("Operators/Comma_Operator", ",")}}
-
The comma operator allows multiple expressions to be evaluated in a single statement and returns the result of the last expression.
-
- -

Non-standard features

- -
-
{{non-standard_inline}} {{jsxref("Operators/Legacy_generator_function", "Legacy generator function", "", 1)}}
-
The function keyword can be used to define a legacy generator function inside an expression. To make the function a legacy generator, the function body should contains at least one {{jsxref("Operators/yield", "yield")}} expression.
-
{{non-standard_inline}} {{jsxref("Operators/Expression_closures", "Expression closures", "", 1)}}
-
The expression closure syntax is a shorthand for writing simple function.
-
{{non-standard_inline}} {{jsxref("Operators/Array_comprehensions", "[for (x of y) x]")}}
-
Array comprehensions.
-
{{non-standard_inline}} {{jsxref("Operators/Generator_comprehensions", "(for (x of y) y)")}}
-
Generator comprehensions.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES1', '#sec-11', 'Expressions')}}{{Spec2('ES1')}}Initial definition
{{SpecName('ES5.1', '#sec-11', 'Expressions')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ES6')}}New: Spread operator, destructuring assignment, super keyword.
{{SpecName('ESDraft', '#sec-ecmascript-language-expressions', 'ECMAScript Language: Expressions')}}{{Spec2('ESDraft')}} 
- -

See also

- - diff --git a/files/vi/web/javascript/reference/operators/operator_precedence/index.html b/files/vi/web/javascript/reference/operators/operator_precedence/index.html deleted file mode 100644 index efa25029b2..0000000000 --- a/files/vi/web/javascript/reference/operators/operator_precedence/index.html +++ /dev/null @@ -1,477 +0,0 @@ ---- -title: Operator precedence -slug: Web/JavaScript/Reference/Operators/Operator_Precedence -translation_of: Web/JavaScript/Reference/Operators/Operator_Precedence ---- -
{{jsSidebar ("Toán tử")}}
- -

Mức độ ưu tiên của toán tử xác định cách các toán tử được phân tích cú pháp liên quan đến nhau. Các toán tử có mức độ ưu tiên cao hơn trở thành toán hạng của các toán tử có mức độ ưu tiên thấp hơn.

- -
{{EmbedInteractiveExample ("pages / js / expression-operatorprecedence.html")}}
- - - -

Precedence And Associativity

- -

Consider an expression describable by the representation below. Note that both OP1 and OP2 are fill-in-the-blanks for OPerators.

- -
a OP1 b OP2 c
- -

If OP1 and OP2 have different precedence levels (see the table below), the operator with the highest precedence goes first and associativity does not matter. Observe how multiplication has higher precedence than addition and executed first, even though addition is written first in the code.

- -
console.log(3 + 10 * 2);   // logs 23
-console.log(3 + (10 * 2)); // logs 23 because parentheses here are superfluous
-console.log((3 + 10) * 2); // logs 26 because the parentheses change the order
-
- -

Left-associativity (left-to-right) means that it is processed as (a OP1 b) OP2 c, while right-associativity (right-to-left) means it is interpreted as a OP1 (b OP2 c). Assignment operators are right-associative, so you can write:

- -
a = b = 5; // same as writing a = (b = 5);
-
- -

with the expected result that a and b get the value 5. This is because the assignment operator returns the value that is assigned. First, b is set to 5. Then the a is also set to 5, the return value of b = 5, aka right operand of the assignment.

- -

As another example, the unique exponentiation operator has right-associativity, whereas other arithmetic operators have left-associativity. It is interesting to note that, the order of evaluation is always left-to-right irregardless of associativity.

- - - - - - - - - - - - - - - - -
CodeOutput
-
-function echo(name, num) {
-    console.log("Evaluating the " + name + " side");
-    return num;
-}
-// Notice the division operator (/)
-console.log(echo("left", 6) / echo("right", 2));
-
-
-
-Evaluating the left side
-Evaluating the right side
-3
-
-
-
-function echo(name, num) {
-    console.log("Evaluating the " + name + " side");
-    return num;
-}
-// Notice the exponentiation operator (**)
-console.log(echo("left", 2) ** echo("right", 3));
-
-
-Evaluating the left side
-Evaluating the right side
-8
-
- -

The difference in associativity comes into play when there are multiple operators of the same precedence. With only one operator or operators of different precedences, associativity doesn't affect the output, as seen in the example above. In the example below, observe how associativity affects the output when multiple of the same operator are used.

- - - - - - - - - - - - - - - - - - - - -
CodeOutput
-
-function echo(name, num) {
-    console.log("Evaluating the " + name + " side");
-    return num;
-}
-// Notice the division operator (/)
-console.log(echo("left", 6) / echo("middle", 2) / echo("right", 3));
-
-
-
-Evaluating the left side
-Evaluating the middle side
-Evaluating the right side
-1
-
-
-
-function echo(name, num) {
-    console.log("Evaluating the " + name + " side");
-    return num;
-}
-// Notice the exponentiation operator (**)
-console.log(echo("left", 2) ** echo("middle", 3) ** echo("right", 2));
-
-
-
-Evaluating the left side
-Evaluating the middle side
-Evaluating the right side
-512
-
-
-
-function echo(name, num) {
-    console.log("Evaluating the " + name + " side");
-    return num;
-}
-// Notice the parentheses around the left and middle exponentiation
-console.log((echo("left", 2) ** echo("middle", 3)) ** echo("right", 2));
-
-
-Evaluating the left side
-Evaluating the middle side
-Evaluating the right side
-64
-
- -

Looking at the code snippets above, 6 / 3 / 2 is the same as (6 / 3) / 2 because division is left-associative. Exponentiation, on the other hand, is right-associative, so 2 ** 3 ** 2 is the same as 2 ** (3 ** 2). Thus, doing (2 ** 3) ** 2 changes the order and results in the 64 seen in the table above.

- -

Remember that precedence comes before associativity. So, mixing division and exponentiation, the exponentiation comes before the division. For example, 2 ** 3 / 3 ** 2 results in 0.8888888888888888 because it is the same as (2 ** 3) / (3 ** 2).

- -

Note on grouping and short-circuiting

- -

In the table below, Grouping is listed as having the highest precedence. However, that does not always mean the expression within the grouping symbols ( … ) is evaluated first, especially when it comes to short-circuiting.

- -

Short-circuiting is jargon for conditional evaluation. For example, in the expression a && (b + c), if a is {{Glossary("falsy")}}, then the sub-expression (b + c) will not even get evaluated, even if it is in parentheses. We could say that the logical disjunction operator ("OR") is "short-circuited". Along with logical disjunction, other short-circuited operators include logical conjunction ("AND"), nullish-coalescing, optional chaining, and the conditional operator. Some more examples follow.

- -
a || (b * c);  // evaluate `a` first, then produce `a` if `a` is "truthy"
-a && (b < c);  // evaluate `a` first, then produce `a` if `a` is "falsy"
-a ?? (b || c); // evaluate `a` first, then produce `a` if `a` is not `null` and not `undefined`
-a?.b.c;        // evaluate `a` first, then produce `undefined` if `a` is `null` or `undefined`
-
- -

Examples

- -
3 > 2 && 2 > 1
-// returns true
-
-3 > 2 > 1
-// Returns false because 3 > 2 is true, then true is converted to 1
-// in inequality operators, therefore true > 1 becomes 1 > 1, which
-//  is false. Adding parentheses makes things clear: (3 > 2) > 1.
-
- -

Table

- -

The following table is ordered from highest (21) to lowest (1) precedence.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
PrecedenceOperator typeAssociativityIndividual operators
21{{jsxref("Operators/Grouping", "Grouping", "", 1)}}n/a( … )
20{{jsxref("Operators/Property_Accessors", "Member Access", "#Dot_notation", 1)}}left-to-right… . …
{{jsxref("Operators/Property_Accessors", "Computed Member Access","#Bracket_notation", 1)}}left-to-right… [ … ]
{{jsxref("Operators/new","new")}} (with argument list)n/anew … ( … )
Function Callleft-to-right… ( )
Optional chainingleft-to-right?.
19{{jsxref("Operators/new","new")}} (without argument list)right-to-leftnew …
18{{jsxref("Operators/Arithmetic_Operators","Postfix Increment","#Increment", 1)}}n/a… ++
{{jsxref("Operators/Arithmetic_Operators","Postfix Decrement","#Decrement", 1)}}… --
17Logical NOTright-to-left! …
Bitwise NOT~ …
Unary Plus+ …
Unary Negation- …
Prefix Increment++ …
Prefix Decrement-- …
{{jsxref("Operators/typeof", "typeof")}}typeof …
{{jsxref("Operators/void", "void")}}void …
{{jsxref ("Toán tử / xóa", "xóa")}}delete …
{{jsxref ("Toán tử / await", "await")}}await …
16Luỹ thừaphải sang trái… ** …
15Phép nhântrái sang phải… * …
Sư đoàn… / …
Phần còn lại… % …
14Thêm vàotrái sang phải… + …
Phép trừ… - …
13Dịch chuyển sang trái theo chiều bittrái sang phải… << …
Chuyển sang phải theo chiều bit… >> …
Chuyển sang phải không dấu bit… >>> …
12Ít hơntrái sang phải… < …
Nhỏ hơn hoặc bằng… <= …
Lớn hơn… > …
Lớn hơn hoặc bằng… >= …
{{jsxref ("Toán tử / trong", "trong")}}… in …
{{jsxref ("Toán tử / instanceof", "instanceof")}}… instanceof …
11Bình đẳngtrái sang phải… == …
Bất bình đẳng… != …
Bình đẳng nghiêm ngặt… === …
Bất bình đẳng nghiêm ngặt… !== …
10Bitwise VÀtrái sang phải… & …
9Bitwise XORtrái sang phải… ^ …
số 8Bitwise HOẶCtrái sang phải… | …
7Logic ANDtrái sang phải… && …
6Logic HOẶCtrái sang phải… || …
5Nhà điều hành liên kết Nullishtrái sang phải… ?? …
4Có điều kiệnphải sang trái… ? … : …
3Chuyển nhượngphải sang trái… = …
… += …
… -= …
… **= …
… *= …
… /= …
… %= …
… <<= …
… >>= …
… >>>= …
… &= …
… ^= …
… |= …
… &&= …
… ||= …
… ??= …
2{{jsxref ("Toán tử / lợi nhuận", "lợi nhuận")}}phải sang tráiyield …
{{jsxref ("Toán tử / lợi nhuận *", "lợi nhuận *")}}yield* …
1Dấu phẩy / Chuỗitrái sang phải… , …
diff --git a/files/vi/web/javascript/reference/operators/super/index.html b/files/vi/web/javascript/reference/operators/super/index.html deleted file mode 100644 index 4e5a092475..0000000000 --- a/files/vi/web/javascript/reference/operators/super/index.html +++ /dev/null @@ -1,226 +0,0 @@ ---- -title: super -slug: Web/JavaScript/Reference/Operators/super -translation_of: Web/JavaScript/Reference/Operators/super ---- -
{{jsSidebar("Operators")}}
- -

Từ khóa super được sử dụng để gọi các hàm trên đối tượng cha.

- -

Các biểu thức super.prop và super[expr] là hợp lệ trong mọi định nghĩa phương thức ở cả classesobject literals.

- -

Cú pháp

- -
super([arguments]); // gọi hàm khởi tạo cha.
-super.functionOnParent([arguments]);
-
- -

Mô tả

- -

Khi được sử dụng trong một hàm khởi tạo, từ khóa super xuất hiện một mình và phải được sử dụng trước khi từ khóa this có thể sử dụng. Từ khóa này cũng có thể được sử dụng để gọi các hàm trên đối tượng cha.

- -

Ví dụ

- -

Sử dụng super trong classes

- -

Đoạn code này lấy từ ví dụ về class (live demo).  super()  ở đây được gọi để tránh việc lặp lại các phần giống nhau của Rectangle và Square.

- -
class Polygon {
-  constructor(height, width) {
-    this.name = 'Polygon';
-    this.height = height;
-    this.width = width;
-  }
-  sayName() {
-    console.log('Hi, I am a ', this.name + '.');
-  }
-}
-
-class Square extends Polygon {
-  constructor(length) {
-    this.height; // ReferenceError, super needs to be called first!
-
-    // Here, it calls the parent class' constructor with lengths
-    // provided for the Polygon's width and height
-    super(length, length);
-
-    // Note: In derived classes, super() must be called before you
-    // can use 'this'. Leaving this out will cause a reference error.
-    this.name = 'Square';
-  }
-
-  get area() {
-    return this.height * this.width;
-  }
-
-  set area(value) {
-    this.area = value;
-  }
-}
- -

Gọi super trên các phương thức tĩnh

- -

Bạn cũng có thể gọi super() trên các phương thức tĩnh.

- -
class Human {
-  constructor() {}
-  static ping() {
-    return 'ping';
-  }
-}
-
-class Computer extends Human {
-  constructor() {}
-  static pingpong() {
-    return super.ping() + ' pong';
-  }
-}
-Computer.pingpong(); // 'ping pong'
-
- -

Xóa các thuộc tính của super sẽ gây ra lỗi

- -

Bạn không thể sử dụng thao tác deletesuper.prop hoặc super[expr] để xóa một thuộc tính của lớp cha, nó sẽ ném lỗi {{jsxref("ReferenceError")}}.

- -
class Base {
-  constructor() {}
-  foo() {}
-}
-class Derived extends Base {
-  constructor() {}
-  delete() {
-    delete super.foo;
-  }
-}
-
-new Derived().delete(); // ReferenceError: invalid delete involving 'super'. 
- -

Super.prop không thể ghi đè các thuộc tính non-writable

- -

Khi định nghĩa các thuộc tính non-writable ví dụ {{jsxref("Object.defineProperty")}},  super không thể ghi đè giá trị của thuộc tính này.

- -
class X {
-  constructor() {
-    Object.defineProperty(this, "prop", {
-      configurable: true,
-      writable: false,
-      value: 1
-    });
-  }
-  f() {
-    super.prop = 2;
-  }
-}
-
-var x = new X();
-x.f();
-console.log(x.prop); // 1
-
- -

Sử dụng super.prop trong object literals

- -

Super cũng có thể được sử dụng trong khởi tạo đối tượng hoặc literal. Trong ví dụ này, 2 đối tượng định nghĩa một phương thức. Trong đối tượng thứ hai,  super gọi phương thức của đối tượng thứ nhất. Điều này làm được với sự trợ giúp của {{jsxref("Object.setPrototypeOf()")}} cái giúp chúng ta có thể thiết lập prototype của obj2 thành obj1, vì thế super có thể tìm method1 trên obj1.

- -
var obj1 = {
-  method1() {
-    console.log("method 1");
-  }
-}
-
-var obj2 = {
-  method2() {
-   super.method1();
-  }
-}
-
-Object.setPrototypeOf(obj2, obj1);
-obj2.method2(); // logs "method 1"
-
- -

Thông số kỹ thuật

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES6', '#sec-super-keyword', 'super')}}{{Spec2('ES6')}}Initial definition.
{{SpecName('ESDraft', '#sec-super-keyword', 'super')}}{{Spec2('ESDraft')}} 
- -

Khả năng tương thích của các trình duyệt

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
Tính năngChromeFirefox (Gecko)Internet ExplorerOperaSafari
Hỗ trợ cơ bản{{CompatChrome(42.0)}}{{CompatGeckoDesktop(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
Tính năngAndroidAndroid WebviewFirefox Mobile (Gecko)IE MobileOpera MobileSafari MobileChrome for Android
Hỗ trợ cơ bản{{CompatUnknown}}{{CompatChrome(42.0)}}{{CompatGeckoMobile(45)}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(42.0)}}
-
- -

Lưu ý cho Gecko

- - - -

Xem thêm

- - diff --git a/files/vi/web/javascript/reference/operators/this/index.html b/files/vi/web/javascript/reference/operators/this/index.html deleted file mode 100644 index d3112507cb..0000000000 --- a/files/vi/web/javascript/reference/operators/this/index.html +++ /dev/null @@ -1,382 +0,0 @@ ---- -title: this -slug: Web/JavaScript/Reference/Operators/this -translation_of: Web/JavaScript/Reference/Operators/this ---- -
{{jsSidebar("Operators")}}
- -

Từ khoá this của hàm  trong JavaScript hơi khác so với các ngôn ngữ khác. Nó cũng có  một vài điểm khác nhau giữa 2 chế độ strict mode và non-strict mode.

- -

Trong hầu hết các trường hợp, giá trị của this được xác định bởi cách gọi hàm (runtime binding). Nó không thể được thiết lập bằng cách gán trong khi thực thi, và nó có thể khác nhau mỗi lần hàm được gọi. ES5 giới thiệu phương thức {{jsxref("Function.prototype.bind()", "bind()")}} để thiết lập giá trị của this bất kể hàm được gọi thế nào, và ES2015 giới thiệu arrow functions mà không cung cấp ràng buộc với this của chúng (Nó sẽ giữ giá trị this của lexical context kèm theo).

- -
{{EmbedInteractiveExample("pages/js/expressions-this.html")}}
- - - -

Cú pháp

- -
this
- -

Giá trị

- -

Một thuộc tính của bối cảnh thực thi (global, function or eval), trong non–strict mode, luôn luôn tham chiếu tới một đối tượng và trong strict mode có thể là bất kỳ giá trị nào.

- -

Global context

- -

Trong global context (bên ngoài các hàm), this tham chiếu tới global object cho dù trong strict mode hoặc không.

- -
// Trong trình duyệt, đối tượng window ?là global object:
-console.log(this === window); // true
-
-a = 37;
-console.log(window.a); // 37
-
-this.b = "MDN";
-console.log(window.b)  // "MDN"
-console.log(b)         // "MDN"
-
- -
-

Note: Bạn có thể dễ dàng lấy được  global object bằng cách sử dụng thuộc tính toàn cầu {{jsxref("globalThis")}}, bất kể bối cảnh hiện tại mà mã của bạn đang chạy.

-
- -

Function context

- -

Bên trong một hàm, giá trị của this phụ thuộc vào cách gọi hàm.

- -

Simple call

- -

Vì đoạn mã sau không ở chế độ strict mode, và vì  giá trị của this không được thiết lập khi gọi, this mặc định là global objecct, đó là window trong trình duyệt. 

- -
function f1() {
-  return this;
-}
-
-// In a browser:
-f1() === window; // true
-
-// In Node:
-f1() === global; // true
- -

Tuy nhiên, trong chế độ strict mode, nếu giá trị của this không được thiết lập khi vào bối cảnh thực thi, nó sẽ giữ giá trị undefined, như ví dụ sau:

- -
function f2() {
-  'use strict'; // see strict mode
-  return this;
-}
-
-f2() === undefined; // true
-
- -
 Trong ví dụ thứ 2, this nên là {{jsxref("undefined")}}, bởi vì f2 được gọi 1 cách trực tiếp và không phải là một phương thức hoặc thuộc tính của một đối tượng(ví dụ window.f2()). ?Tính năng này sẽ không được triển khai trong một số trình duyệt khi chúng lần đầu hỗ trợ chế độ strict mode. Như kết quả trên, chúng không trả về đối tượng window.
- -

Để thiết lập giá trị cụ thể của this khi gọi hàm, sử dụng {{jsxref("Function.prototype.call()", "call()")}}, hoặc {{jsxref("Function.prototype.apply()", "apply()")}} như các ví dụ dưới đây.

- -

Example 1

- -
// Một đối tượng có thể truyền vào như là tham số đầu tiên của call hoặc apply và this sẽ được ràng buộc với nó..
-var obj = {a: 'Custom'};
-
-// Thuộc tính này được thiết lập trên global object
-var a = 'Global';
-
-function whatsThis() {
-  return this.a;  // Giá trị của this phụ thuộc vào cách hàm được gọi.
-}
-
-whatsThis();          // 'Global'
-whatsThis.call(obj);  // 'Custom'
-whatsThis.apply(obj); // 'Custom'
-
- -

Example 2

- -
function add(c, d) {
-  return this.a + this.b + c + d;
-}
-
-var o = {a: 1, b: 3};
-
-// Tham số đầu tiên là đối tượng sử dụng như là
-// 'this', tham số tiếp theo được truyền vào là
-// đối số trong hàm gọi
-add.call(o, 5, 7); // 16
-
-// Tham số đầu tiên là đối tượng sử dụng như là
-// 'this', tham số thứ 2 là 1 mảng
-// các phần tử được sử dụng làm đối số trong lệnh gọi hàm
-add.apply(o, [10, 20]); // 34
-
- -

 Chú ý trong chế độ  non–strict mode, với call và apply, nếu giá trị được truyền vào this không phải là đối tượng, một nỗ lực sẽ được thực hiện để chuyển đổi nó thành đối tượng bằng cách sử dụng ToObject. Vì thế nếu bạn truyền vào giá trị primitive như 7 hoặc 'foo', nó sẽ được chuyển đổi thành Object bằng cách sử dụng các constructor liên quan, do đó 7 sẽ được chuyển đổi thành đối tượng như tạo bằng new Number(7) và string 'foo' cũng được chuyển đổi thành đối tượng như tạo bằng new String('foo'), ví dụ:

- -
function bar() {
-  console.log(Object.prototype.toString.call(this));
-}
-
-bar.call(7);     // [object Number]
-bar.call('foo'); // [object String]
-
- -

The bind method

- -

ECMAScript 5 giới thiệu {{jsxref("Function.prototype.bind()")}}. Gọi f.bind(someObject) tạo ra một hàm mới với cùng thân hàm và phạm vi như hàm f, nhưng this chỉ xảy ra trong hàm ban đầu, trong những hàm mới nó bị ràng buộc vĩnh viễn với đối số đầu tiên của bind, bất kể các hàm được sử dụng thế nào..

- -
function f() {
-  return this.a;
-}
-
-var g = f.bind({a: 'azerty'});
-console.log(g()); // azerty
-
-var h = g.bind({a: 'yoo'}); // bind only works once!
-console.log(h()); // azerty
-
-var o = {a: 37, f: f, g: g, h: h};
-console.log(o.a, o.f(), o.g(), o.h()); // 37,37, azerty, azerty
-
- -

Arrow functions

- -

Trong arrow functions, this giữ giá trị ?this của lexical context kèm theo. Trong đoạn mã toàn cục, nó sẽ được thiết lập là global object.

- -
var globalObject = this;
-var foo = (() => this);
-console.log(foo() === globalObject); // true
- -
-

 Lưu ý: nếu đối số  this được truyền vào call, bind, hoặc apply ?trong việc gọi một arrow function nó sẽ bị bỏ qua. Bạn vẫn có thể thêm các đối số cho việc gọi hàm nhưng đối số đầu tiên (thisArg) nên được đặt thành null.

-
- -
// Call as a method of an object
-var obj = {func: foo};
-console.log(obj.func() === globalObject); // true
-
-// Attempt to set this using call
-console.log(foo.call(obj) === globalObject); // true
-
-// Attempt to set this using bind
-foo = foo.bind(obj);
-console.log(foo() === globalObject); // true
- -

Không có vấn đề gì ở đây, this của foo vẫn giữ nguyên giá trị khi nó được tạo  (trong ví dụ trên, nó là global object). Điều tương tự cũng được áp dụng cho những arrow function được tạo bên trong hàm khác: this của chúng giữ giá trị this của lexical context kèm theo.

- -
// Tạo 1 đối tượng với phương thức bar trả về 1 hàm, hàm này sẽ
-// trả về this của nó. Hàm trả về là arrow function,
-// vì thế this của nó được ràng buộc vĩnh viễn với this của hàm kèm theo.
-// Giá trị của bar có thể được thiết lập trong khi gọi hàm,
-// lần lượt đặt giá của hàm trả về.
-var obj = {
-  bar: function() {
-    var x = (() => this);
-    return x;
-  }
-};
-
-// Gọi phương thức bar của obj, thiết lập this là obj.
-// Gán một tham chiếu tới hàm trả về là fn
-var fn = obj.bar();
-
-// Gọi hàm fn mà không thiết lập 'this',
-// thông thường sẽ mặc định cho global object hoặc undefined trong strict mode
-console.log(fn() === obj); // true
-
-// Nhưng hãy cẩn thận nếu bạn tham chiếu phương thức của đối tượng mà không gọi nó
-var fn2 = obj.bar;
-// Gọi hàm arrow function bên trong phương thức bar()
-// nó sẽ trả về window, bởi vì nó theo 'this' từ fn2.
-console.log(fn2()() == window); // true
-
- -

Trong ví dụ trên, hàm (gọi nó là hàm ẩn danh A) gán cho obj.bar trả về một hàm khác (gọi là hàm ẩn danh B) mà nó là một arrow function. Kết quả là, this của hàm B được thiết lập vĩnh viễn là this của obj.bar (hàm A) khi được gọi. Khi hàm trả về (hàm B)  được gọi, this của nó sẽ luôn là  những gì được thiết lập ban đầu. Trong đoạn mã trên, this của hàm B được thiết lập theo this của hàm A đó là obj, vì thế nó vẫn được thiết lập là obj ngay cả khi được gọi  theo cách thông thường thiết lập this thành undefined hoặc global object (hoặc bất kỳ phương thức nào khác như trong ví dụ trên được thực thi trong bối cảnh toàn cầu).

- -

As an object method

- -

Khi một hàm được gọi như là một phương thức của đối tượng,this được đặt thành đối tượng mà có phương thức được gọi trên.

- -

Trong ví dụ dưới đây, khi o.f() được gọi, this bên trong hàm sẽ liên kết với đối tượng o.

- -
var o = {
-  prop: 37,
-  f: function() {
-    return this.prop;
-  }
-};
-
-console.log(o.f()); // 37
-
- -

Lưu ý hành vi này hoàn toàn không bị ảnh hưởng bởi cách thức hoặc nơi chức năng được khai báo. Trong ví dụ ở trên, chúng ta khai báo hàm f bên trong đối tượng o. Tuy nhiên, chúng ta có thể dễ dàng khai báo hàm trước và đính kèm nó vào o.f. Làm như vậy sẽ có kết quả tương tự:

- -
var o = {prop: 37};
-
-function independent() {
-  return this.prop;
-}
-
-o.f = independent;
-
-console.log(o.f()); // 37
-
- -

Điều này chứng tỏ rằng vấn đề chỉ là việc gọi hàm f của o.

- -

Tương tự, ràng buộc với this chỉ bị ảnh hưởng bởi tham chiếu trực tiếp nhất. Trong ví dụ dưới, khi chúng ta gọi hàm, chúng ta gọi nó như là một phương thức g của đối tượng o.b. Khi thực thi, this bên trong hàm sẽ tham chiếu tới o.b. Thực tế đối tượng này là một thành viên của o không ảnh hưởng; tham chiếu trực tiếp nhất mới là quan trọng nhất.

- -
var o = {prop: 37};
-function independent() { return this.prop; }
-o.f = independent;
-console.log(o.f()); // 37 bởi vì tham chiếu trực tiếp nhất là o
-o.b = {g: independent, prop: 42};
-console.log(o.b.g()); // 42 bởi vì tham chiếu trực tiếp nhất là o.b
-
- -

this on the object's prototype chain

- -

The same notion holds true for methods defined somewhere on the object's prototype chain. If the method is on an object's prototype chain, this refers to the object the method was called on, as if the method were on the object.

- -
var o = {f: function() { return this.a + this.b; }};
-var p = Object.create(o);
-p.a = 1;
-p.b = 4;
-
-console.log(p.f()); // 5
-
- -

In this example, the object assigned to the variable p doesn't have its own f property, it inherits it from its prototype. But it doesn't matter that the lookup for f eventually finds a member with that name on o; the lookup began as a reference to p.f, so this inside the function takes the value of the object referred to as p. That is, since f is called as a method of p, its this refers to p. This is an interesting feature of JavaScript's prototype inheritance.

- -

this with a getter or setter

- -

Again, the same notion holds true when a function is invoked from a getter or a setter. A function used as getter or setter has its this bound to the object from which the property is being set or gotten.

- -
function sum() {
-  return this.a + this.b + this.c;
-}
-
-var o = {
-  a: 1,
-  b: 2,
-  c: 3,
-  get average() {
-    return (this.a + this.b + this.c) / 3;
-  }
-};
-
-Object.defineProperty(o, 'sum', {
-    get: sum, enumerable: true, configurable: true});
-
-console.log(o.average, o.sum); // 2, 6
-
- -

As a constructor

- -

When a function is used as a constructor (with the {{jsxref("Operators/new", "new")}} keyword), its this is bound to the new object being constructed.

- -
-

While the default for a constructor is to return the object referenced by this, it can instead return some other object (if the return value isn't an object, then the this object is returned).

-
- -
/*
- * Constructors work like this:
- *
- * function MyConstructor(){
- *   // Actual function body code goes here.
- *   // Create properties on |this| as
- *   // desired by assigning to them.  E.g.,
- *   this.fum = "nom";
- *   // et cetera...
- *
- *   // If the function has a return statement that
- *   // returns an object, that object will be the
- *   // result of the |new| expression.  Otherwise,
- *   // the result of the expression is the object
- *   // currently bound to |this|
- *   // (i.e., the common case most usually seen).
- * }
- */
-
-function C() {
-  this.a = 37;
-}
-
-var o = new C();
-console.log(o.a); // 37
-
-
-function C2() {
-  this.a = 37;
-  return {a: 38};
-}
-
-o = new C2();
-console.log(o.a); // 38
-
- -

In the last example (C2), because an object was returned during construction, the new object that this was bound to simply gets discarded. (This essentially makes the statement "this.a = 37;" dead code. It's not exactly dead because it gets executed, but it can be eliminated with no outside effects.)

- -

As a DOM event handler

- -

When a function is used as an event handler, its this is set to the element on which the listener is placed (some browsers do not follow this convention for listeners added dynamically with methods other than addEventListener()).

- -
// When called as a listener, turns the related element blue
-function bluify(e) {
-  // Always true
-  console.log(this === e.currentTarget);
-  // true when currentTarget and target are the same object
-  console.log(this === e.target);
-  this.style.backgroundColor = '#A5D9F3';
-}
-
-// Get a list of every element in the document
-var elements = document.getElementsByTagName('*');
-
-// Add bluify as a click listener so when the
-// element is clicked on, it turns blue
-for (var i = 0; i < elements.length; i++) {
-  elements[i].addEventListener('click', bluify, false);
-}
- -

In an inline event handler

- -

When the code is called from an inline on-event handler, its this is set to the DOM element on which the listener is placed:

- -
<button onclick="alert(this.tagName.toLowerCase());">
-  Show this
-</button>
-
- -

The above alert shows button. Note however that only the outer code has its this set this way:

- -
<button onclick="alert((function() { return this; })());">
-  Show inner this
-</button>
-
- -

In this case, the inner function's this isn't set so it returns the global/window object (i.e. the default object in non–strict mode where this isn't set by the call).

- -

Specifications

- - - - - - - - - - -
Specification
{{SpecName('ESDraft', '#sec-this-keyword', 'The this keyword')}}
- -

Browser compatibility

- - - -

{{Compat("javascript.operators.this")}}

- -

See also

- - diff --git a/files/vi/web/javascript/reference/operators/typeof/index.html b/files/vi/web/javascript/reference/operators/typeof/index.html deleted file mode 100644 index e949879669..0000000000 --- a/files/vi/web/javascript/reference/operators/typeof/index.html +++ /dev/null @@ -1,271 +0,0 @@ ---- -title: typeof -slug: Web/JavaScript/Reference/Operators/typeof -translation_of: Web/JavaScript/Reference/Operators/typeof ---- -
{{jsSidebar("Operators")}}
- -

Phương thức typeof trả về kiểu dữ liệu của đối tượng nào đó.

- -
{{EmbedInteractiveExample("pages/js/expressions-typeof.html")}}
- - - -

Cú pháp

- -

Phương thức typeof được theo sau bởi toán hạng operand:

- -
typeof operand
-typeof(operand)
-
- -

Các tham số

- -
-
operand
-
Là một đối tượng cần kiểu tra kiểu dữ liệu hoặc một biểu thức đại điện cho đối tượng.
-
- -

Định nghĩa

- -

Bảng tóm tắt bên dưới mô tả các giá trị có thể trả về của typeof. Xem thêm thông tin tại trang JavaScript data structure.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
TypeResult
{{glossary("Undefined")}}"undefined"
{{glossary("Null")}}"object" (see {{anch("null", "below")}})
{{glossary("Boolean")}}"boolean"
{{glossary("Number")}}"number"
{{glossary("BigInt")}}"bigint"
{{glossary("String")}}"string"
{{glossary("Symbol")}} (new in ECMAScript 2015)"symbol"
Host object (provided by the JS environment)Implementation-dependent
{{glossary("Function")}} object (implements [[Call]] in ECMA-262 terms)"function"
Any other object"object"
- -

Các ví dụ

- -
// Numbers
-typeof 37 === 'number';
-typeof 3.14 === 'number';
-typeof(42) === 'number';
-typeof Math.LN2 === 'number';
-typeof Infinity === 'number';
-typeof NaN === 'number'; // Mặc dù "Not-A-Number" nhưng lại là number :)
-typeof Number('1') === 'number'; // Number ép kiểu chuỗi thành kiểu number
-
-typeof 42n === 'bigint';
-
-
-// Strings
-typeof '' === 'string';
-typeof 'bla' === 'string';
-typeof `template literal` === 'string';
-typeof '1' === 'string'; // 1 là number nhưng khi nằm trong ngoặc '' sẽ thành kiểu string
-typeof (typeof 1) === 'string'; // typeof 1 sẽ trả về chữ number, bạn tự hiểu được hen
-typeof String(1) === 'string'; // String sẽ đổi kiểu số 1 từ number thành string
-
-// Booleans
-typeof true === 'boolean';
-typeof false === 'boolean';
-typeof Boolean(1) === 'boolean'; // Boolean() will convert values based on if they're truthy or falsy
-typeof !!(1) === 'boolean'; // two calls of the ! (logical NOT) operator are equivalent to Boolean()
-
-
-// Symbols
-typeof Symbol() === 'symbol'
-typeof Symbol('foo') === 'symbol'
-typeof Symbol.iterator === 'symbol'
-
-
-// Undefined
-typeof undefined === 'undefined';
-typeof declaredButUndefinedVariable === 'undefined';
-typeof undeclaredVariable === 'undefined';
-
-
-// Objects
-typeof {a: 1} === 'object';
-
-// use Array.isArray or Object.prototype.toString.call
-// to differentiate regular objects from arrays
-typeof [1, 2, 4] === 'object';
-
-typeof new Date() === 'object';
-typeof /regex/ === 'object'; // See Regular expressions section for historical results
-
-
-// The following are confusing, dangerous, and wasteful. Avoid them.
-typeof new Boolean(true) === 'object';
-typeof new Number(1) === 'object';
-typeof new String('abc') === 'object';
-
-
-// Functions
-typeof function() {} === 'function';
-typeof class C {} === 'function';
-typeof Math.sin === 'function';
-
- -

Additional information

- -

null

- -
// This stands since the beginning of JavaScript
-typeof null === 'object';
-
- -

In the first implementation of JavaScript, JavaScript values were represented as a type tag and a value. The type tag for objects was 0. null was represented as the NULL pointer (0x00 in most platforms). Consequently, null had 0 as type tag, hence the "object" typeof return value. (reference)

- -

A fix was proposed for ECMAScript (via an opt-in), but was rejected. It would have resulted in typeof null === 'null'.

- -

Using new operator

- -
// All constructor functions, with the exception of the Function constructor, will always be typeof 'object'
-var str = new String('String');
-var num = new Number(100);
-
-typeof str; // It will return 'object'
-typeof num; // It will return 'object'
-
-var func = new Function();
-
-typeof func; // It will return 'function'
-
- -

Need for parentheses in Syntax

- -
// Parentheses can be used for determining the data type of expressions.
-var iData = 99;
-
-typeof iData + ' Wisen'; // 'number Wisen'
-typeof (iData + ' Wisen'); // 'string'
-
- -

Regular expressions

- -

Callable regular expressions were a non-standard addition in some browsers.

- -
typeof /s/ === 'function'; // Chrome 1-12 Non-conform to ECMAScript 5.1
-typeof /s/ === 'object';   // Firefox 5+  Conform to ECMAScript 5.1
-
- -

Errors

- -

Before ECMAScript 2015, typeof was always guaranteed to return a string for any operand it was supplied with. Even with undeclared identifiers, typeof will return 'undefined'. Using typeof could never generate an error.

- -

But with the addition of block-scoped {{jsxref("Statements/let", "let")}} and {{jsxref("Statements/const")}} using typeof on let and const variables (or using typeof on a class) in a block before they are declared will throw a {{jsxref("ReferenceError")}}. Block scoped variables are in a "temporal dead zone" from the start of the block until the initialization is processed, during which, it will throw an error if accessed.

- -
typeof undeclaredVariable === 'undefined';
-
-typeof newLetVariable; // ReferenceError
-typeof newConstVariable; // ReferenceError
-typeof newClass; // ReferenceError
-
-let newLetVariable;
-const newConstVariable = 'hello';
-class newClass{};
- -

Exceptions

- -

All current browsers expose a non-standard host object {{domxref("document.all")}} with type undefined.

- -
typeof document.all === 'undefined';
-
- -

Although the specification allows custom type tags for non-standard exotic objects, it requires those type tags to be different from the predefined ones. The case of document.all having type 'undefined' is classified in the web standards as a "willful violation" of the original ECMA JavaScript standard.

- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ESDraft', '#sec-typeof-operator', 'The typeof Operator')}}{{Spec2('ESDraft')}}
{{SpecName('ES6', '#sec-typeof-operator', 'The typeof Operator')}}{{Spec2('ES6')}}
{{SpecName('ES5.1', '#sec-11.4.3', 'The typeof Operator')}}{{Spec2('ES5.1')}}
{{SpecName('ES3', '#sec-11.4.3', 'The typeof Operator')}}{{Spec2('ES3')}}
{{SpecName('ES1', '#sec-11.4.3', 'The typeof Operator')}}{{Spec2('ES1')}}Initial definition. Implemented in JavaScript 1.1.
- -

Browser compatibility

- - - -

{{Compat("javascript.operators.typeof")}}

- -

IE-specific notes

- -

On IE 6, 7, and 8 a lot of host objects are objects and not functions. For example:

- -
typeof alert === 'object'
- -

See also

- - diff --git a/files/vi/web/javascript/reference/statements/async_function/index.html b/files/vi/web/javascript/reference/statements/async_function/index.html deleted file mode 100644 index 3009b78083..0000000000 --- a/files/vi/web/javascript/reference/statements/async_function/index.html +++ /dev/null @@ -1,255 +0,0 @@ ---- -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 deleted file mode 100644 index d6afd506d7..0000000000 --- a/files/vi/web/javascript/reference/statements/continue/index.html +++ /dev/null @@ -1,135 +0,0 @@ ---- -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 deleted file mode 100644 index eef8cf1f08..0000000000 --- a/files/vi/web/javascript/reference/statements/do...while/index.html +++ /dev/null @@ -1,98 +0,0 @@ ---- -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 deleted file mode 100644 index 0187b3dbfa..0000000000 --- a/files/vi/web/javascript/reference/statements/export/index.html +++ /dev/null @@ -1,186 +0,0 @@ ---- -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 deleted file mode 100644 index 5bd72040eb..0000000000 --- a/files/vi/web/javascript/reference/statements/for...of/index.html +++ /dev/null @@ -1,318 +0,0 @@ ---- -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 deleted file mode 100644 index 613732de85..0000000000 --- a/files/vi/web/javascript/reference/statements/for/index.html +++ /dev/null @@ -1,137 +0,0 @@ ---- -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 deleted file mode 100644 index 388e0f8b34..0000000000 --- a/files/vi/web/javascript/reference/statements/function_star_/index.html +++ /dev/null @@ -1,208 +0,0 @@ ---- -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 deleted file mode 100644 index 460884b7d9..0000000000 --- a/files/vi/web/javascript/reference/statements/index.html +++ /dev/null @@ -1,143 +0,0 @@ ---- -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 deleted file mode 100644 index c3116c8847..0000000000 --- a/files/vi/web/javascript/reference/statements/throw/index.html +++ /dev/null @@ -1,193 +0,0 @@ ---- -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

- - diff --git a/files/vi/web/javascript/reference/template_literals/index.html b/files/vi/web/javascript/reference/template_literals/index.html deleted file mode 100644 index 3626937740..0000000000 --- a/files/vi/web/javascript/reference/template_literals/index.html +++ /dev/null @@ -1,238 +0,0 @@ ---- -title: Template literals (Template strings) -slug: Web/JavaScript/Reference/Template_literals -translation_of: Web/JavaScript/Reference/Template_literals ---- -
{{JsSidebar("More")}}
- -

Mẫu nguyên thủy là chuỗi string nguyên thủy cho phép áp dụng vào các biểu thức. Bạn có thể sử dụng các chuỗi nhiều dòng và các chuỗi chức năng nội suy với chúng. Chúng được gọi là "chuỗi mẫu" trong các phiên bản trước của đặc tả ES2015.

- -

Cú pháp

- -
`string text`
-
-`string text line 1
- string text line 2`
-
-`string text ${expression} string text`
-
-tag `string text ${expression} string text`
-
- -

Mô tả

- -

Mẫu nguyên thủy được đóng bởi dấu 'nháy-ngược' (` `)  (grave accent - nằm ở góc trái dưới phím Esc) thay vì sử dụng nháy đơn hoặc nháy kép. Mẫunguyên thủy có thể bao gồm placeholders (trong thẻ input có 1 thuộc tính placeholder). Chúng được biểu thị bằng ký hiệu đô la và dấu ngoặc nhọn (${expression}). Các biểu thức trong placeholders và văn bản giữa các dấu 'nháy-ngược' (` `) được đưa vào hàm. Hàm mặc định chỉ ghép các thành phần thành một chuỗi đơn. Nếu có một biểu thức thực hiện trước một mẫu nguyên thủy (tag - ở đây gọi là thẻ), thì được gọi là một "tagged template" (mẫu được gắn thẻ). Trong trường hợp này, biểu thức gắn thẻ (thường là một hàm) được gọi cùng với mẫu nguyên thủy, biểu thức mà sau đó bạn có thể thao tác trước khi trả ra kết quả. Để thoát dấu 'nháy-ngược' trong một mẫu nguyên thủy, hãy đặt dấu gạch chéo ngược \ trước dấu nháyngược (phần này nên note lại và cần tham khảo thêm các ví dụ sau).

- -
`\`` === '`' // --> true
- -

Các chuỗi nhiều dòng (chuỗi đa dòng)

- -

Bất kỳ các dòng ký tự mới được chèn vào trong nguồn (mã nguồn) đều là một phần của mẫu nguyên thủy. Việc sử dụng các chuỗi mặc định, bạn sẽ phải sử dụng các cú pháp dưới đây để có được các chuỗi đa dòng (sử dụng ký tự \n):

- -
console.log('string text line 1\n' +
-'string text line 2');
-// "string text line 1
-// string text line 2"
- -

Để có được kết quả tượng tự thì sử dụng cú pháp mẫu nguyên thủy, bạn có thể viết như sau:

- -
console.log(`string text line 1
-string text line 2`);
-// "string text line 1
-// string text line 2"
- -

Biểu thức nội suy

- -

Để nhúng các thiểu thức (hàm, phép tính, ...) vào trong chuỗi mặc định, bạn sẽ sử dụng cú pháp dưới đây:

- -
var a = 5;
-var b = 10;
-console.log('Fifteen is ' + (a + b) + ' and\nnot ' + (2 * a + b) + '.');
-// "Fifteen is 15 and
-// not 20."
- -

Giờ đây, với các mẫu nguyên thủy, bạn có thể sử dụng các thay thế cú pháp như thế này để dễ đọc hơn:

- -
var a = 5;
-var b = 10;
-console.log(`Fifteen is ${a + b} and
-not ${2 * a + b}.`);
-// "Fifteen is 15 and
-// not 20."
- -

Các mẫu lồng nhau (mẫu nằm trong mẫu khác)

- -

Trong một số trường hợp nhất định, lồng một mẫu là cách dễ nhất và có thể dễ đọc hơn để có các chuỗi có khả năng cấu hình. Bên trong một mẫu được tạo, nó đơn giản để cho phép các dấu nháy ngược bên trong chỉ đơn giản bằng cách sử dụng chúng trong một placeholder ${ } bên trong mẫu. Ví dụ, nếu điều kiện đúng: thì trả về mẫu nguyên thủy.

- -

Trong ES5:

- -
var classes = 'header'
-classes += (isLargeScreen() ?
-   '' : item.isCollapsed ?
-     ' icon-expander' : ' icon-collapser');
-
- -

Trong ES2015 với mẫu nguyên thủy và không đặt lồng nhau:

- -
const classes = `header ${ isLargeScreen() ? '' :
-    (item.isCollapsed ? 'icon-expander' : 'icon-collapser') }`;
- -

Trong ES2015 với 2 mẫu nguyên thủy đặt lồng nhau:

- -
const classes = `header ${ isLargeScreen() ? '' :
- `icon-${item.isCollapsed ? 'expander' : 'collapser'}` }`;
- -

Các mẫu được gắn thẻ

- -

Một hình thức nâng cao hơn của mẫu nguyên thủy là các mẫu được gắn thẻ. Các thẻ cho phép bạn chuyển đổi các mẫu nguyên thủy sử dụng hàm. Tham số đầu tiên của hàm gắn thẻ bao gồm một mảng các chuỗi. Các tham số còn lại được gắn với các biểu thức. Cuối cùng, hàm của bạn có thể trả về chuỗi được thao tác (hoặc nó có thể trả về bất kỳ kết quả gì theo mục đích lập trình trong ví dụ tiếp theo).  Tê của hàm được sử dụng cho thẻ bạn có thể đặt tên theo cách bạn muốn.

- -
var person = 'Mike';
-var age = 28;
-
-function myTag(strings, personExp, ageExp) {
-  var str0 = strings[0]; // "That "
-  var str1 = strings[1]; // " is a "
-
-  // There is technically a string after
-  // the final expression (in our example),
-  // but it is empty (""), so disregard.
-  // var str2 = strings[2];
-
-  var ageStr;
-  if (ageExp > 99){
-    ageStr = 'centenarian';
-  } else {
-    ageStr = 'youngster';
-  }
-
-  // We can even return a string built using a template literal
-  return `${str0}${personExp}${str1}${ageStr}`;
-}
-
-var output = myTag`That ${ person } is a ${ age }`;
-
-console.log(output);
-// That Mike is a youngster
- -

Các hàm gắn thẻ không cần trả về một chuỗi, như được hiển thị ở ví dụ dưới đây.

- -
function template(strings, ...keys) {
-  return (function(...values) {
-    var dict = values[values.length - 1] || {};
-    var result = [strings[0]];
-    keys.forEach(function(key, i) {
-      var value = Number.isInteger(key) ? values[key] : dict[key];
-      result.push(value, strings[i + 1]);
-    });
-    return result.join('');
-  });
-}
-
-var t1Closure = template`${0}${1}${0}!`;
-t1Closure('Y', 'A');  // "YAY!"
-var t2Closure = template`${0} ${'foo'}!`;
-t2Closure('Hello', {foo: 'World'});  // "Hello World!"
-
- -

Các chuỗi chưa xử lý (chuỗi thô)

- -

thuộc tính raw khá đặc biệt, có thể trong tham số đầu tiên để gán thẻ hàm, nó cho phép bạn truy cập các chuỗi thô như khi chúng được đưa vào, không cần sử lý escape sequences.

- -
function tag(strings) {
-  console.log(strings.raw[0]);
-}
-
-tag`string text line 1 \n string text line 2`;
-// logs "string text line 1 \n string text line 2" ,
-// including the two characters '\' and 'n'
-
- -

Ngoài ra, phương thức {{jsxref("String.raw()")}} tồn tại để tạo các chuỗi thô giống như hàm mẫu mặc định và chuỗi nối.

- -
var str = String.raw`Hi\n${2+3}!`;
-// "Hi\n5!"
-
-str.length;
-// 6
-
-str.split('').join(',');
-// "H,i,\,n,5,!"
-
- -

Mẫu được gắn thẻ và trình tự thoát

- -

ES2016 behavior

- -

Trong ECMAScript 2016, các mẫu được gắn thẻ tuân theo quy tắc của các trình tự thoát sau đây:

- - - -

Điều này có nghĩa là một mẫu được gắn thẻ như sau là có vấn đề, bởi vì mỗi ngữ pháp ECMAScript, một phân tích trông như đúng trình tự Unicode escape:

- -
latex`\unicode`
-// Throws in older ECMAScript versions (ES2016 and earlier)
-// SyntaxError: malformed Unicode character escape sequence
- -

ES2018 sửa đổi các chuỗi thoát bất hợp pháp

- -

Các mẫu được gắn thẻ sẽ cho phép nhúng các ngôn ngữ (ví dụ DSLs, or LaTeX), trong đó các chuỗi thoát khác là phổ biến. ECMAScript đề xuất Template Literal Revision (giai đoạn 4, được tích hợp trong tiêu chuẩn ECMAScript 2018) xóa giới hạn cú pháp của chuỗi thoát ECMAScript khỏi các mẫu được gắn thẻ.

- -

Tuy nhiên, các chuỗi thoát bất hợp pháp vẫn phải được giữ lại. Chúng sẽ hiển thị như thành phần {{jsxref("undefined")}} trong mảng “cooked”:

- -
function latex(str) {
- return { "cooked": str[0], "raw": str.raw[0] }
-}
-
-latex`\unicode`
-
-// { cooked: undefined, raw: "\\unicode" }
- -

Chú ý rằng hạn chế trình tự thoát chỉ được loại bỏ khỏi các mẫu được gắn thẻ chứ không phải từ các mẫu chữ không được đánh dấu:

- -
let bad = `bad escape sequence: \unicode`;
- -

Thông số kỹ thuật

- - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('ES2015', '#sec-template-literals', 'Template Literals')}}{{Spec2('ES2015')}}Initial definition. Defined in several section of the specification: Template Literals, Tagged Templates
{{SpecName('ESDraft', '#sec-template-literals', 'Template Literals')}}{{Spec2('ESDraft')}}Defined in several section of the specification: Template Literals, Tagged Templates
- -

Browser compatibility

- -
- - -

{{Compat("javascript.grammar.template_literals")}}

-
- -

See also

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