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) --- .../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 ----- 84 files changed, 15073 deletions(-) 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 (limited to 'files/vi/web/javascript/reference/global_objects') 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

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