diff --git a/1-js/05-data-types/04-array/1-item-value/solution.md b/1-js/05-data-types/04-array/1-item-value/solution.md index e631f1c70..43a7e3055 100644 --- a/1-js/05-data-types/04-array/1-item-value/solution.md +++ b/1-js/05-data-types/04-array/1-item-value/solution.md @@ -1,17 +1,16 @@ -The result is `4`: +Kết quả là `4`: ```js run -let fruits = ["Apples", "Pear", "Orange"]; +let fruits = ["Táo", "Lê", "Cam"]; let shoppingCart = fruits; -shoppingCart.push("Banana"); +shoppingCart.push("Chuối"); *!* alert( fruits.length ); // 4 */!* ``` -That's because arrays are objects. So both `shoppingCart` and `fruits` are the references to the same array. - +Đó là bởi vì array là đối tượng. Vì vậy, cả `shoppingCart` và `fruits` đều là các tham chiếu đến cùng một array. diff --git a/1-js/05-data-types/04-array/1-item-value/task.md b/1-js/05-data-types/04-array/1-item-value/task.md index 4fcf384fb..2d03c1a34 100644 --- a/1-js/05-data-types/04-array/1-item-value/task.md +++ b/1-js/05-data-types/04-array/1-item-value/task.md @@ -2,18 +2,17 @@ importance: 3 --- -# Is array copied? +# Array có được sao chép không? -What is this code going to show? +Mã này sẽ hiển thị là gì? ```js -let fruits = ["Apples", "Pear", "Orange"]; +let fruits = ["Táo", "Lê", "Cam"]; -// push a new value into the "copy" +// đẩy một giá trị mới vào "bản sao" let shoppingCart = fruits; -shoppingCart.push("Banana"); +shoppingCart.push("Chuối"); -// what's in fruits? +// có gì trong fruits? alert( fruits.length ); // ? ``` - diff --git a/1-js/05-data-types/04-array/10-maximal-subarray/solution.md b/1-js/05-data-types/04-array/10-maximal-subarray/solution.md index befd80296..97dd54bfe 100644 --- a/1-js/05-data-types/04-array/10-maximal-subarray/solution.md +++ b/1-js/05-data-types/04-array/10-maximal-subarray/solution.md @@ -1,43 +1,43 @@ -# Slow solution +# Giải pháp chậm -We can calculate all possible subsums. +Chúng ta có thể tính toán tất cả các tổng con có thể. -The simplest way is to take every element and calculate sums of all subarrays starting from it. +Cách đơn giản nhất là lấy mọi phần tử và tính tổng của tất cả các array con bắt đầu từ nó. -For instance, for `[-1, 2, 3, -9, 11]`: +Chẳng hạn, đối với `[-1, 2, 3, -9, 11]`: ```js no-beautify -// Starting from -1: +// Bắt đầu từ -1: -1 -1 + 2 -1 + 2 + 3 -1 + 2 + 3 + (-9) -1 + 2 + 3 + (-9) + 11 -// Starting from 2: +// Bắt đầu từ 2: 2 2 + 3 2 + 3 + (-9) 2 + 3 + (-9) + 11 -// Starting from 3: +// Bắt đầu từ 3: 3 3 + (-9) 3 + (-9) + 11 -// Starting from -9 +// Bắt đầu từ -9 -9 -9 + 11 -// Starting from 11 +// Bắt đầu từ 11 11 ``` -The code is actually a nested loop: the external loop over array elements, and the internal counts subsums starting with the current element. +Mã thực sự là một vòng lặp lồng nhau: vòng lặp bên ngoài trên các phần tử array và bên trong đếm các tổng con bắt đầu bằng phần tử hiện tại. ```js run function getMaxSubSum(arr) { - let maxSum = 0; // if we take no elements, zero will be returned + let maxSum = 0; // nếu chúng ta không lấy phần tử nào, số 0 sẽ được trả về for (let i = 0; i < arr.length; i++) { let sumFixedStart = 0; @@ -57,25 +57,25 @@ alert( getMaxSubSum([1, 2, 3]) ); // 6 alert( getMaxSubSum([100, -9, 2, -3, 5]) ); // 100 ``` -The solution has a time complexity of [O(n2)](https://en.wikipedia.org/wiki/Big_O_notation). In other words, if we increase the array size 2 times, the algorithm will work 4 times longer. +Giải pháp có độ phức tạp về thời gian là [O(n2)](https://vi.wikipedia.org/wiki/Kí_hiệu_O_lớn). Nói cách khác, nếu chúng ta tăng kích thước array lên 2 lần, thuật toán sẽ hoạt động lâu hơn 4 lần. -For big arrays (1000, 10000 or more items) such algorithms can lead to a serious sluggishness. +Đối với các array lớn (1000, 10000 mục trở lên), các thuật toán như vậy có thể dẫn đến tình trạng chậm chạp nghiêm trọng. -# Fast solution +# Giải pháp nhanh chóng -Let's walk the array and keep the current partial sum of elements in the variable `s`. If `s` becomes negative at some point, then assign `s=0`. The maximum of all such `s` will be the answer. +Hãy di chuyển array và giữ tổng một phần hiện tại của các phần tử trong biến `s`. Nếu `s` trở thành số âm tại một thời điểm nào đó, thì hãy gán `s=0`. Tối đa của tất cả `s` như vậy sẽ là câu trả lời. -If the description is too vague, please see the code, it's short enough: +Nếu mô tả quá mơ hồ, hãy xem mã, nó đủ ngắn: ```js run demo function getMaxSubSum(arr) { let maxSum = 0; let partialSum = 0; - for (let item of arr) { // for each item of arr - partialSum += item; // add it to partialSum - maxSum = Math.max(maxSum, partialSum); // remember the maximum - if (partialSum < 0) partialSum = 0; // zero if negative + for (let item of arr) { // cho mỗi mục của arr + partialSum += item; // thêm nó vào partialSum + maxSum = Math.max(maxSum, partialSum); // ghi nhớ số tối đa + if (partialSum < 0) partialSum = 0; // trả về không nếu âm } return maxSum; @@ -89,6 +89,6 @@ alert( getMaxSubSum([1, 2, 3]) ); // 6 alert( getMaxSubSum([-1, -2, -3]) ); // 0 ``` -The algorithm requires exactly 1 array pass, so the time complexity is O(n). +Thuật toán yêu cầu chính xác 1 lần truyền array, vì vậy độ phức tạp về thời gian là O(n). -You can find more detail information about the algorithm here: [Maximum subarray problem](http://en.wikipedia.org/wiki/Maximum_subarray_problem). If it's still not obvious why that works, then please trace the algorithm on the examples above, see how it works, that's better than any words. +Bạn có thể tìm thêm thông tin chi tiết về thuật toán tại đây: [Vấn đề array con tối đa](http://en.wikipedia.org/wiki/Maximum_subarray_problem). Nếu vẫn chưa rõ tại sao nó hoạt động, thì hãy theo dõi thuật toán trên các ví dụ trên, xem nó hoạt động như thế nào, điều đó tốt hơn bất kỳ từ nào. diff --git a/1-js/05-data-types/04-array/10-maximal-subarray/task.md b/1-js/05-data-types/04-array/10-maximal-subarray/task.md index f1a1d9f95..4fda66ae4 100644 --- a/1-js/05-data-types/04-array/10-maximal-subarray/task.md +++ b/1-js/05-data-types/04-array/10-maximal-subarray/task.md @@ -2,29 +2,29 @@ importance: 2 --- -# A maximal subarray +# Một array con tối đa -The input is an array of numbers, e.g. `arr = [1, -2, 3, 4, -9, 6]`. +Đầu vào là một dãy số, ví dụ: `array = [1, -2, 3, 4, -9, 6]`. -The task is: find the contiguous subarray of `arr` with the maximal sum of items. +Nhiệm vụ là: tìm array con liền kề của `arr` với tổng các phần tử lớn nhất. -Write the function `getMaxSubSum(arr)` that will return that sum. +Viết hàm `getMaxSubSum(arr)` sẽ trả về tổng đó. -For instance: +Ví dụ: ```js -getMaxSubSum([-1, *!*2, 3*/!*, -9]) == 5 (the sum of highlighted items) +getMaxSubSum([-1, *!*2, 3*/!*, -9]) == 5 (tổng các mục được đánh dấu) getMaxSubSum([*!*2, -1, 2, 3*/!*, -9]) == 6 getMaxSubSum([-1, 2, 3, -9, *!*11*/!*]) == 11 getMaxSubSum([-2, -1, *!*1, 2*/!*]) == 3 getMaxSubSum([*!*100*/!*, -9, 2, -3, 5]) == 100 -getMaxSubSum([*!*1, 2, 3*/!*]) == 6 (take all) +getMaxSubSum([*!*1, 2, 3*/!*]) == 6 (lấy tất cả) ``` -If all items are negative, it means that we take none (the subarray is empty), so the sum is zero: +Nếu tất cả các mục đều âm, điều đó có nghĩa là chúng ta không lấy gì (array con trống), vì vậy tổng bằng 0: ```js getMaxSubSum([-1, -2, -3]) = 0 ``` -Please try to think of a fast solution: [O(n2)](https://en.wikipedia.org/wiki/Big_O_notation) or even O(n) if you can. +Vui lòng thử nghĩ ra một giải pháp nhanh chóng: [O(n2)](https://vi.wikipedia.org/wiki/Kí_hiệu_O_lớn) hoặc thậm chí là O(n) nếu có thể. diff --git a/1-js/05-data-types/04-array/2-create-array/task.md b/1-js/05-data-types/04-array/2-create-array/task.md index 16d14071f..f1a36617f 100644 --- a/1-js/05-data-types/04-array/2-create-array/task.md +++ b/1-js/05-data-types/04-array/2-create-array/task.md @@ -2,17 +2,17 @@ importance: 5 --- -# Array operations. +# Các phép toán array. -Let's try 5 array operations. +Hãy thử 5 phép toán array. -1. Create an array `styles` with items "Jazz" and "Blues". -2. Append "Rock-n-Roll" to the end. -3. Replace the value in the middle by "Classics". Your code for finding the middle value should work for any arrays with odd length. -4. Strip off the first value of the array and show it. -5. Prepend `Rap` and `Reggae` to the array. +1. Tạo một array `style` với các mục "Jazz" và "Blues". +2. Nối "Rock-n-Roll" vào cuối. +3. Thay giá trị ở giữa với "Classics". Mã của bạn để tìm giá trị ở giữa sẽ hoạt động đối với bất kỳ array nào có độ dài lẻ. +4. Tách giá trị đầu tiên của array và hiển thị nó. +5. Thêm `Rap` và `Reggae` vào array. -The array in the process: +Array trong quá trình: ```js no-beautify Jazz, Blues diff --git a/1-js/05-data-types/04-array/3-call-array-this/solution.md b/1-js/05-data-types/04-array/3-call-array-this/solution.md index 3cb0317cf..c05df0680 100644 --- a/1-js/05-data-types/04-array/3-call-array-this/solution.md +++ b/1-js/05-data-types/04-array/3-call-array-this/solution.md @@ -1,6 +1,6 @@ -The call `arr[2]()` is syntactically the good old `obj[method]()`, in the role of `obj` we have `arr`, and in the role of `method` we have `2`. +Lệnh gọi `arr[2]()` về mặt cú pháp là `obj[method]()` cũ và tốt, ở vai trò `obj` chúng ta có `arr` và ở vai trò `method` chúng ta có `2` . -So we have a call of the function `arr[2]` as an object method. Naturally, it receives `this` referencing the object `arr` and outputs the array: +Vì vậy, chúng ta có một lệnh gọi hàm `arr[2]` như một phương thức đối tượng. Đương nhiên, nó nhận được `this` tham chiếu đến đối tượng `arr` và xuất ra array: ```js run let arr = ["a", "b"]; @@ -12,4 +12,4 @@ arr.push(function() { arr[2](); // a,b,function(){...} ``` -The array has 3 values: initially it had two, plus the function. +Array có 3 giá trị: ban đầu nó có hai giá trị, cộng với hàm. diff --git a/1-js/05-data-types/04-array/3-call-array-this/task.md b/1-js/05-data-types/04-array/3-call-array-this/task.md index 340c5feef..a51ed7c80 100644 --- a/1-js/05-data-types/04-array/3-call-array-this/task.md +++ b/1-js/05-data-types/04-array/3-call-array-this/task.md @@ -2,17 +2,16 @@ importance: 5 --- -# Calling in an array context +# Gọi trong ngữ cảnh array -What is the result? Why? +Kết quả là gì? Tại sao? ```js let arr = ["a", "b"]; arr.push(function() { alert( this ); -}) +}); arr[2](); // ? ``` - diff --git a/1-js/05-data-types/04-array/5-array-input-sum/solution.md b/1-js/05-data-types/04-array/5-array-input-sum/solution.md index 75bd683b5..82ad257a5 100644 --- a/1-js/05-data-types/04-array/5-array-input-sum/solution.md +++ b/1-js/05-data-types/04-array/5-array-input-sum/solution.md @@ -1,4 +1,4 @@ -Please note the subtle, but important detail of the solution. We don't convert `value` to number instantly after `prompt`, because after `value = +value` we would not be able to tell an empty string (stop sign) from the zero (valid number). We do it later instead. +Hãy lưu ý chi tiết tinh tế nhưng quan trọng của giải pháp. Chúng ta không chuyển đổi `giá trị` thành số ngay sau `dấu nhắc`, bởi vì sau `giá trị = +giá trị`, chúng ta sẽ không thể phân biệt một chuỗi trống (dấu dừng) với số không (số hợp lệ). Thay vào đó, chúng ta làm điều đó sau. ```js run demo @@ -8,9 +8,9 @@ function sumInput() { while (true) { - let value = prompt("A number please?", 0); + let value = prompt("Xin vui lòng nhập một số?", 0); - // should we cancel? + // chúng ta có nên hủy không? if (value === "" || value === null || !isFinite(value)) break; numbers.push(+value); @@ -25,4 +25,3 @@ function sumInput() { alert( sumInput() ); ``` - diff --git a/1-js/05-data-types/04-array/5-array-input-sum/task.md b/1-js/05-data-types/04-array/5-array-input-sum/task.md index 4af8e7c95..5ee52d480 100644 --- a/1-js/05-data-types/04-array/5-array-input-sum/task.md +++ b/1-js/05-data-types/04-array/5-array-input-sum/task.md @@ -2,14 +2,14 @@ importance: 4 --- -# Sum input numbers +# Tổng số đầu vào -Write the function `sumInput()` that: +Viết hàm `sumInput()` để: -- Asks the user for values using `prompt` and stores the values in the array. -- Finishes asking when the user enters a non-numeric value, an empty string, or presses "Cancel". -- Calculates and returns the sum of array items. +- Hỏi người dùng các giá trị bằng cách sử dụng `prompt` và lưu trữ các giá trị trong array. +- Kết thúc hỏi khi người dùng nhập giá trị không phải là số, chuỗi rỗng hoặc nhấn "Hủy". +- Tính toán và trả về tổng của các phần tử array. -P.S. A zero `0` is a valid number, please don't stop the input on zero. +Tái bút: Số không `0` là một số hợp lệ, vui lòng không dừng đầu vào ở số không. [demo] diff --git a/1-js/05-data-types/04-array/array-pop.svg b/1-js/05-data-types/04-array/array-pop.svg index 82b112b4a..f2d69ac85 100644 --- a/1-js/05-data-types/04-array/array-pop.svg +++ b/1-js/05-data-types/04-array/array-pop.svg @@ -1 +1 @@ -0123"Apple""Orange""Pear""Lemon"length = 4clear012"Apple""Orange""Pear"length = 3 \ No newline at end of file +0123"Táo""Cam""Lê""Chanh"length = 4xóa012"Táo""Cam""Lê"length = 3 diff --git a/1-js/05-data-types/04-array/array-shift.svg b/1-js/05-data-types/04-array/array-shift.svg index 9485a3c96..1408d4807 100644 --- a/1-js/05-data-types/04-array/array-shift.svg +++ b/1-js/05-data-types/04-array/array-shift.svg @@ -1 +1 @@ -123"Orange""Pear""Lemon"length = 423"Orange""Pear""Lemon"length = 3clearmove elements to the left0"Apple"012"Orange""Pear""Lemon"11 \ No newline at end of file +123"Cam""Lê""Chanh"length = 423"Cam""Lê""Chanh"length = 3xóadi chuyểncác yếu tố qua bên trái0"Táo"012"Cam""Lê""Chanh"11 diff --git a/1-js/05-data-types/04-array/article.md b/1-js/05-data-types/04-array/article.md index d722341bb..24394c00e 100644 --- a/1-js/05-data-types/04-array/article.md +++ b/1-js/05-data-types/04-array/article.md @@ -1,286 +1,318 @@ -# Arrays +# Array -Objects allow you to store keyed collections of values. That's fine. +Các đối tượng cho phép bạn lưu trữ các bộ sưu tập giá trị có khóa. Tốt rồi. -But quite often we find that we need an *ordered collection*, where we have a 1st, a 2nd, a 3rd element and so on. For example, we need that to store a list of something: users, goods, HTML elements etc. +Nhưng khá thường xuyên, chúng ta thấy rằng chúng ta cần một *bộ sưu tập được sắp xếp theo thứ tự*, trong đó chúng ta có phần tử thứ nhất, thứ hai, thứ ba, v.v. Ví dụ: chúng ta cần điều đó để lưu trữ danh sách thứ gì đó: người dùng, hàng hóa, phần tử HTML, v.v. -It is not convenient to use an object here, because it provides no methods to manage the order of elements. We can’t insert a new property “between” the existing ones. Objects are just not meant for such use. +Sẽ không thuận tiện khi sử dụng một đối tượng ở đây vì nó không cung cấp phương thức nào để quản lý thứ tự của các phần tử. Chúng ta không thể chèn một thuộc tính mới “giữa” những thuộc tính hiện có. Các đối tượng không có nghĩa là để sử dụng như vậy. -There exists a special data structure named `Array`, to store ordered collections. +Tồn tại một cấu trúc dữ liệu đặc biệt có tên là `Array`, để lưu trữ các bộ sưu tập có thứ tự. -## Declaration +## Khai báo -There are two syntaxes for creating an empty array: +Có hai cú pháp để tạo một array trống: ```js let arr = new Array(); let arr = []; ``` -Almost all the time, the second syntax is used. We can supply initial elements in the brackets: +Hầu như mọi lúc, cú pháp thứ hai được sử dụng. Chúng ta có thể cung cấp các yếu tố ban đầu trong ngoặc đơn: ```js -let fruits = ["Apple", "Orange", "Plum"]; +let fruits = ["Táo", "Cam", "Mận"]; ``` -Array elements are numbered, starting with zero. +Các phần tử của array được đánh số, bắt đầu bằng số không. -We can get an element by its number in square brackets: +Chúng ta có thể lấy một phần tử theo số của nó trong ngoặc vuông: ```js run -let fruits = ["Apple", "Orange", "Plum"]; +let fruits = ["Táo", "Cam", "Mận"]; -alert( fruits[0] ); // Apple -alert( fruits[1] ); // Orange -alert( fruits[2] ); // Plum +alert( fruits[0] ); // Táo +alert( fruits[1] ); // Cam +alert( fruits[2] ); // Mận ``` -We can replace an element: +Chúng ta có thể thay thế một phần tử: ```js -fruits[2] = 'Pear'; // now ["Apple", "Orange", "Pear"] +fruits[2] = 'Lê'; // bây giờ là ["Táo", "Cam", "Lê"] ``` -...Or add a new one to the array: +...Hoặc thêm một cái mới vào array: ```js -fruits[3] = 'Lemon'; // now ["Apple", "Orange", "Pear", "Lemon"] +fruits[3] = 'Chanh'; // bây giờ là ["Táo", "Cam", "Lê", "Chanh"] ``` -The total count of the elements in the array is its `length`: +Tổng số phần tử trong array là `length` của nó: ```js run -let fruits = ["Apple", "Orange", "Plum"]; +let fruits = ["Táo", "Cam", "Mận"]; alert( fruits.length ); // 3 ``` -We can also use `alert` to show the whole array. +Chúng ta cũng có thể sử dụng `alert` để hiển thị toàn bộ array. ```js run -let fruits = ["Apple", "Orange", "Plum"]; +let fruits = ["Táo", "Cam", "Mận"]; -alert( fruits ); // Apple,Orange,Plum +alert( fruits ); // Táo,Cam,Mận ``` -An array can store elements of any type. +Một array có thể lưu trữ các phần tử thuộc bất kỳ kiểu nào. -For instance: +Ví dụ: ```js run no-beautify -// mix of values -let arr = [ 'Apple', { name: 'John' }, true, function() { alert('hello'); } ]; +// hỗn hợp các giá trị +let arr = [ 'Táo', { tên: 'John' }, true, function() { alert('xin chào'); } ]; -// get the object at index 1 and then show its name +// lấy đối tượng ở chỉ mục 1 và sau đó hiển thị tên của nó alert( arr[1].name ); // John -// get the function at index 3 and run it -arr[3](); // hello +// lấy hàm ở chỉ mục 3 và chạy nó +arr[3](); // xin chào ``` -````smart header="Trailing comma" -An array, just like an object, may end with a comma: +````smart header="Dấu phẩy ở cuối" +Một array, giống như một đối tượng, có thể kết thúc bằng dấu phẩy: ```js let fruits = [ - "Apple", - "Orange", - "Plum"*!*,*/!* + "Táo", + "Cam", + "Mận"*!*,*/!* ]; ``` -The "trailing comma" style makes it easier to insert/remove items, because all lines become alike. +Kiểu "dấu phẩy ở cuối" giúp chèn/xóa các mục dễ dàng hơn vì tất cả các dòng đều giống nhau. ```` +## Nhận các phần tử cuối cùng với "at" -## Methods pop/push, shift/unshift +[recent browser="new"] -A [queue](https://en.wikipedia.org/wiki/Queue_(abstract_data_type)) is one of the most common uses of an array. In computer science, this means an ordered collection of elements which supports two operations: +Giả sử chúng ta muốn phần tử cuối cùng của array. -- `push` appends an element to the end. -- `shift` get an element from the beginning, advancing the queue, so that the 2nd element becomes the 1st. +Một số ngôn ngữ lập trình cho phép việc sử dụng chỉ mục âm cho cùng một mục đích, chẳng hạn như `trái cây[-1]`. + +Mặc dù, trong JavaScript nó sẽ không hoạt động. Kết quả sẽ là `undefined`, bởi vì chỉ mục trong ngoặc vuông được xử lý theo nghĩa đen. + +Chúng ta có thể tính toán chỉ mục phần tử cuối cùng một cách rõ ràng và sau đó truy cập nó: `fruits[fruits.length - 1]`. + +```js run +let fruits = ["Táo", "Cam", "Mận"]; +alert( fruits[fruits.length-1] ); // Mận +``` + +Hơi rườm rà phải không? Chúng ta cần viết tên biến tới hai lần. + +May mắn thay, có một cú pháp ngắn hơn: `fruits.at(-1)`: + +```js run +let fruits = ["Táo", "Cam", "Mận"]; +// giống như fruits[fruits.length-1] +alert( fruits.at(-1) ); // Mận +``` + +Nói cách khác, `arr.at(i)`: +- hoàn toàn giống với `arr[i]`, nếu `i >= 0`. +- đối với các giá trị âm của `i`, nó lùi lại từ cuối array. + +## Các phương thức pop/push, shift/unshift + + [Hàng đợi](https://vi.wikipedia.org/wiki/Hàng đợi) là một trong những cách sử dụng array phổ biến nhất. Trong khoa học máy tính, điều này có nghĩa là một tập hợp các phần tử được sắp xếp theo thứ tự hỗ trợ hai thao tác: + +- `push` nối một phần tử vào cuối. +- `shift` lấy phần tử từ đầu, tăng hàng đợi, sao cho phần tử thứ 2 trở thành phần tử thứ nhất. ![](queue.svg) -Arrays support both operations. +Array hỗ trợ cả hai hành động. -In practice we need it very often. For example, a queue of messages that need to be shown on-screen. +Trong thực tế, chúng ta cần nó rất thường xuyên. Ví dụ: một hàng tin nhắn cần được hiển thị trên màn hình. -There's another use case for arrays -- the data structure named [stack](https://en.wikipedia.org/wiki/Stack_(abstract_data_type)). +Có một trường hợp sử dụng khác cho array -- cấu trúc dữ liệu có tên [ngăn xếp](https://vi.wikipedia.org/wiki/Ngăn_xếp). -It supports two operations: +Nó hỗ trợ hai hành động: -- `push` adds an element to the end. -- `pop` takes an element from the end. +- `push` thêm một phần tử vào cuối. +- `pop` lấy một phần tử từ cuối. -So new elements are added or taken always from the "end". +Vì vậy, các yếu tố mới được thêm vào hoặc lấy luôn từ "cuối". -A stack is usually illustrated as a pack of cards: new cards are added to the top or taken from the top: +Một ngăn xếp thường được minh họa dưới dạng một bộ bài: các quân bài mới được thêm vào trên cùng hoặc lấy ra từ trên cùng: ![](stack.svg) -For stacks, the latest pushed item is received first, that's also called LIFO (Last-In-First-Out) principle. For queues, we have FIFO (First-In-First-Out). +Đối với ngăn xếp, mục được đẩy mới nhất sẽ được nhận trước, đó còn được gọi là nguyên tắc LIFO (Last-In-First-Out). Đối với hàng đợi, chúng ta có FIFO (First-In-First-Out). -Arrays in JavaScript can work both as a queue and as a stack. They allow you to add/remove elements both to/from the beginning or the end. +Array trong JavaScript có thể hoạt động như một hàng đợi và ngăn xếp. Chúng cho phép bạn thêm/xóa các phần tử, cả vào đầu hay cuối. -In computer science the data structure that allows this, is called [deque](https://en.wikipedia.org/wiki/Double-ended_queue). +Trong khoa học máy tính, cấu trúc dữ liệu cho phép điều này được gọi là [deque](https://vi.wikipedia.org/wiki/Hàng_đợi). -**Methods that work with the end of the array:** +**Các phương thức hoạt động với phần cuối của array:** `pop` -: Extracts the last element of the array and returns it: +: Trích xuất phần tử cuối cùng của array và trả về: ```js run - let fruits = ["Apple", "Orange", "Pear"]; + let fruits = ["Táo", "Cam", "Lê"]; - alert( fruits.pop() ); // remove "Pear" and alert it + alert( fruits.pop() ); // loại bỏ "Lê" và alert nó - alert( fruits ); // Apple, Orange + alert( fruits ); // Táo,Cam ``` + Cả `fruits.pop()` và `fruits.at(-1)` đều trả về phần tử cuối cùng của array, nhưng `fruits.pop()` cũng sửa đổi array bằng cách loại bỏ nó. + `push` -: Append the element to the end of the array: +: Nối phần tử vào cuối array: ```js run - let fruits = ["Apple", "Orange"]; + let fruits = ["Táo", "Cam"]; - fruits.push("Pear"); + fruits.push("Lê"); - alert( fruits ); // Apple, Orange, Pear + alert( fruits ); // Táo,Cam,Lê ``` - The call `fruits.push(...)` is equal to `fruits[fruits.length] = ...`. + Cuộc gọi `fruits.push(...)` bằng `fruits[fruits.length] = ...`. -**Methods that work with the beginning of the array:** +**Các phương thức hoạt động với phần đầu của array:** `shift` -: Extracts the first element of the array and returns it: +: Trích xuất phần tử đầu tiên của array và trả về nó: ```js run - let fruits = ["Apple", "Orange", "Pear"]; + let fruits = ["Táo", "Cam", "Lê"]; - alert( fruits.shift() ); // remove Apple and alert it + alert( fruits.shift() ); // xóa Táo và alert nó - alert( fruits ); // Orange, Pear + alert( fruits ); // Táo,Lê ``` `unshift` -: Add the element to the beginning of the array: +: Thêm phần tử vào đầu array: ```js run - let fruits = ["Orange", "Pear"]; + let fruits = ["Cam", "Lê"]; - fruits.unshift('Apple'); + fruits.unshift('Táo'); - alert( fruits ); // Apple, Orange, Pear + alert( fruits ); // Táo,Cam,Lê ``` -Methods `push` and `unshift` can add multiple elements at once: +Các phương thức `push` và `unshift` có thể thêm nhiều phần tử cùng một lúc: ```js run -let fruits = ["Apple"]; +let fruits = ["Táo"]; -fruits.push("Orange", "Peach"); -fruits.unshift("Pineapple", "Lemon"); +fruits.push("Cam", "Lê"); +fruits.unshift("Dứa", "Chanh"); -// ["Pineapple", "Lemon", "Apple", "Orange", "Peach"] +// ["Dứa", "Chanh", "Táo", "Cam", "Lê"] alert( fruits ); ``` -## Internals +## Bên trong -An array is a special kind of object. The square brackets used to access a property `arr[0]` actually come from the object syntax. That's essentially the same as `obj[key]`, where `arr` is the object, while numbers are used as keys. +Array là một loại đối tượng đặc biệt. Dấu ngoặc vuông được sử dụng để truy cập một thuộc tính `arr[0]` thực sự đến từ cú pháp đối tượng. Điều đó về cơ bản giống như `obj[key]`, trong đó `arr` là đối tượng, trong khi các số được sử dụng làm khóa. -They extend objects providing special methods to work with ordered collections of data and also the `length` property. But at the core it's still an object. +Chúng mở rộng các đối tượng cung cấp các phương thức đặc biệt để làm việc với các bộ sưu tập dữ liệu được sắp xếp theo thứ tự và cả thuộc tính `length`. Nhưng cốt lõi nó vẫn là một đối tượng. -Remember, there are only eight basic data types in JavaScript (see the [Data types](info:types) chapter for more info). Array is an object and thus behaves like an object. +Hãy nhớ rằng, chỉ có tám loại dữ liệu cơ bản trong JavaScript (xem chương [Kiểu dữ liệu](info:type) để biết thêm thông tin). Array là một đối tượng và do đó hoạt động như một đối tượng. -For instance, it is copied by reference: +Chẳng hạn, nó được sao chép bằng cách tham chiếu: ```js run -let fruits = ["Banana"] +let fruits = ["Chuối"] -let arr = fruits; // copy by reference (two variables reference the same array) +let arr = fruits; // sao chép theo tham chiếu (hai biến tham chiếu cùng một array) alert( arr === fruits ); // true -arr.push("Pear"); // modify the array by reference +arr.push("Pear"); // sửa đổi array bằng tham chiếu -alert( fruits ); // Banana, Pear - 2 items now +alert( fruits ); // Chuối,Lê - bây giờ có 2 item ``` -...But what makes arrays really special is their internal representation. The engine tries to store its elements in the contiguous memory area, one after another, just as depicted on the illustrations in this chapter, and there are other optimizations as well, to make arrays work really fast. +...Nhưng điều làm cho aray thực sự đặc biệt là biểu diễn bên trong của chúng. Engine cố gắng lưu trữ các phần tử của nó trong vùng bộ nhớ liền kề, lần lượt, giống như được mô tả trên các hình minh họa trong chương này, và cũng có các tối ưu hóa khác, để làm cho các array hoạt động rất nhanh. -But they all break if we quit working with an array as with an "ordered collection" and start working with it as if it were a regular object. +Nhưng tất cả chúng đều hỏng nếu chúng ta ngừng làm việc với một array như với một "bộ sưu tập có thứ tự" và bắt đầu làm việc với nó như thể nó là một đối tượng thông thường. -For instance, technically we can do this: +Chẳng hạn, về mặt kỹ thuật, chúng ta có thể làm điều này: ```js -let fruits = []; // make an array +let fruits = []; // tạo một array -fruits[99999] = 5; // assign a property with the index far greater than its length +fruits[99999] = 5; // chỉ định một thuộc tính có chỉ số lớn hơn nhiều so với độ dài của nó -fruits.age = 25; // create a property with an arbitrary name +fruits.age = 25; // tạo một thuộc tính với một tên tùy ý ``` -That's possible, because arrays are objects at their base. We can add any properties to them. +Điều đó là có thể, bởi vì array là đối tượng ở cơ sở của chúng. Chúng ta có thể thêm bất kỳ thuộc tính nào vào chúng. -But the engine will see that we're working with the array as with a regular object. Array-specific optimizations are not suited for such cases and will be turned off, their benefits disappear. +Nhưng engine sẽ thấy rằng chúng ta đang làm việc với array như với một đối tượng thông thường. Tối ưu hóa theo array cụ thể không phù hợp với những trường hợp như vậy và sẽ bị tắt, lợi ích của chúng sẽ biến mất. -The ways to misuse an array: +Các cách để lạm dụng một array: -- Add a non-numeric property like `arr.test = 5`. -- Make holes, like: add `arr[0]` and then `arr[1000]` (and nothing between them). -- Fill the array in the reverse order, like `arr[1000]`, `arr[999]` and so on. +- Thêm một thuộc tính không phải là số như `arr.test = 5`. +- Tạo lỗ, chẳng hạn như: thêm `arr[0]` và sau đó `arr[1000]` (và không có gì giữa chúng). +- Điền vào array theo thứ tự ngược lại, như `arr[1000]`, `arr[999]`, v.v. -Please think of arrays as special structures to work with the *ordered data*. They provide special methods for that. Arrays are carefully tuned inside JavaScript engines to work with contiguous ordered data, please use them this way. And if you need arbitrary keys, chances are high that you actually require a regular object `{}`. +Hãy coi array là cấu trúc đặc biệt để làm việc với *dữ liệu được sắp xếp*. Chúng cung cấp các phương thức đặc biệt cho điều đó. Array được điều chỉnh cẩn thận bên trong các JavaScript engine để hoạt động với dữ liệu được sắp xếp liền kề, hãy sử dụng chúng theo cách này. Và nếu bạn cần các khóa tùy ý, rất có thể bạn thực sự cần một đối tượng thông thường `{}`. -## Performance +## Hiệu suất -Methods `push/pop` run fast, while `shift/unshift` are slow. +Các phương thức `push/pop` chạy nhanh, trong khi `shift/unshift` chạy chậm. ![](array-speed.svg) -Why is it faster to work with the end of an array than with its beginning? Let's see what happens during the execution: +Tại sao làm việc với phần cuối của một array nhanh hơn so với phần đầu của nó? Hãy xem điều gì xảy ra trong quá trình thực hiện: ```js -fruits.shift(); // take 1 element from the start +fruits.shift(); // lấy 1 phần tử từ phần đầu ``` -It's not enough to take and remove the element with the number `0`. Other elements need to be renumbered as well. +Việc lấy và xóa phần tử có chỉ mục `0` là không đủ. Các yếu tố khác cũng cần được đánh số lại. -The `shift` operation must do 3 things: +Thao tác `shift` phải thực hiện 3 việc: -1. Remove the element with the index `0`. -2. Move all elements to the left, renumber them from the index `1` to `0`, from `2` to `1` and so on. -3. Update the `length` property. +1. Xóa phần tử có chỉ số `0`. +2. Di chuyển tất cả các phần tử sang bên trái, đánh số lại chúng từ chỉ số `1` thành `0`, từ `2` thành `1`, v.v. +3. Cập nhật thuộc tính `length`. ![](array-shift.svg) -**The more elements in the array, the more time to move them, more in-memory operations.** +**Càng nhiều phần tử trong array, càng có nhiều thời gian để di chuyển chúng, nhiều thao tác trong bộ nhớ hơn.** -The similar thing happens with `unshift`: to add an element to the beginning of the array, we need first to move existing elements to the right, increasing their indexes. +Điều tương tự cũng xảy ra với `unshift`: để thêm một phần tử vào đầu array, trước tiên chúng ta cần di chuyển các phần tử hiện có sang bên phải, tăng chỉ số của chúng. -And what's with `push/pop`? They do not need to move anything. To extract an element from the end, the `pop` method cleans the index and shortens `length`. +Và chuyện gì xảy ra với `push/pop`? Chúng không cần phải di chuyển bất cứ cái gì. Để trích xuất một phần tử từ cuối, phương thức `pop` sẽ xóa chỉ mục và rút ngắn `length`. -The actions for the `pop` operation: +Các hành động cho thao tác `pop`: ```js -fruits.pop(); // take 1 element from the end +fruits.pop(); // lấy 1 phần tử từ phần cuối ``` ![](array-pop.svg) -**The `pop` method does not need to move anything, because other elements keep their indexes. That's why it's blazingly fast.** +**Phương thức `pop` không cần di chuyển bất cứ thứ gì, bởi vì các phần tử khác giữ chỉ mục của chúng. Đó là lý do tại sao nó rất nhanh.** -The similar thing with the `push` method. +Điều tương tự với phương thức `push`. -## Loops +## Vòng lặp -One of the oldest ways to cycle array items is the `for` loop over indexes: +Một trong những cách lâu đời nhất để quay vòng các mục array là vòng lặp `for` trên các chỉ mục: ```js run -let arr = ["Apple", "Orange", "Pear"]; +let arr = ["Táo", "Cam", "Lê"]; *!* for (let i = 0; i < arr.length; i++) { @@ -289,103 +321,101 @@ for (let i = 0; i < arr.length; i++) { } ``` -But for arrays there is another form of loop, `for..of`: +Nhưng đối với array thì có một dạng vòng lặp khác, `for..of`: ```js run -let fruits = ["Apple", "Orange", "Plum"]; +let fruits = ["Táo", "Cam", "Mận"]; -// iterates over array elements +// lặp qua các phần tử array for (let fruit of fruits) { alert( fruit ); } ``` -The `for..of` doesn't give access to the number of the current element, just its value, but in most cases that's enough. And it's shorter. +`for..of` không cấp quyền truy cập vào số lượng của phần tử hiện tại, mà chỉ cấp quyền truy cập vào giá trị của phần tử đó, nhưng trong hầu hết các trường hợp, như vậy là đủ. Và nó ngắn hơn. -Technically, because arrays are objects, it is also possible to use `for..in`: +Về mặt kỹ thuật, vì array là đối tượng nên cũng có thể sử dụng `for..in`: ```js run -let arr = ["Apple", "Orange", "Pear"]; + let arr = ["Táo", "Cam", "Lê"]; *!* for (let key in arr) { */!* - alert( arr[key] ); // Apple, Orange, Pear + alert( arr[key] ); // Táo,Cam,Lê } ``` -But that's actually a bad idea. There are potential problems with it: +Nhưng đó thực sự là một ý tưởng tồi. Có những vấn đề tiềm ẩn với nó: -1. The loop `for..in` iterates over *all properties*, not only the numeric ones. +1. Vòng lặp `for..in` lặp qua *tất cả các thuộc tính*, không chỉ các thuộc tính số. - There are so-called "array-like" objects in the browser and in other environments, that *look like arrays*. That is, they have `length` and indexes properties, but they may also have other non-numeric properties and methods, which we usually don't need. The `for..in` loop will list them though. So if we need to work with array-like objects, then these "extra" properties can become a problem. + Có cái gọi là các đối tượng "dạng array" trong trình duyệt và trong các môi trường khác *dạng array*. Nghĩa là, chúng có các thuộc tính `length` và chỉ mục, nhưng chúng cũng có thể có các thuộc tính và phương thức không phải là số khác mà chúng ta thường không cần đến. Mặc dù vậy, vòng lặp `for..in` sẽ liệt kê chúng. Vì vậy, nếu chúng ta cần làm việc với các đối tượng dạng array, thì các thuộc tính "phụ" này có thể trở thành một vấn đề. -2. The `for..in` loop is optimized for generic objects, not arrays, and thus is 10-100 times slower. Of course, it's still very fast. The speedup may only matter in bottlenecks. But still we should be aware of the difference. +2. Vòng lặp `for..in` được tối ưu hóa cho các đối tượng chung, không phải array và do đó chậm hơn 10-100 lần. Tất nhiên, nó vẫn rất nhanh. Việc tăng tốc có thể chỉ quan trọng trong các nút cổ chai. Nhưng chúng ta vẫn nên nhận thức được sự khác biệt. -Generally, we shouldn't use `for..in` for arrays. +Nói chung, chúng ta không nên sử dụng `for..in` cho array. -## A word about "length" +## Một từ về "length" -The `length` property automatically updates when we modify the array. To be precise, it is actually not the count of values in the array, but the greatest numeric index plus one. +Thuộc tính `length` tự động cập nhật khi chúng ta sửa đổi array. Nói một cách chính xác, nó thực sự không phải là số lượng giá trị trong array, mà là chỉ số lớn nhất cộng với một. -For instance, a single element with a large index gives a big length: +Chẳng hạn, một phần tử có chỉ số lớn sẽ cho độ dài lớn: ```js run let fruits = []; -fruits[123] = "Apple"; +fruits[123] = "Táo"; alert( fruits.length ); // 124 ``` -Note that we usually don't use arrays like that. +Lưu ý là chúng ta thường không sử dụng các aray như vậy. -Another interesting thing about the `length` property is that it's writable. +Một điều thú vị khác về thuộc tính `length` là nó có thể ghi được. -If we increase it manually, nothing interesting happens. But if we decrease it, the array is truncated. The process is irreversible, here's the example: +Nếu chúng ta tăng nó theo cách thủ công, sẽ không có gì thú vị xảy ra. Nhưng nếu chúng ta giảm nó, array sẽ bị cắt bớt. Quá trình này là không thể đảo ngược, đây là ví dụ: ```js run let arr = [1, 2, 3, 4, 5]; -arr.length = 2; // truncate to 2 elements +arr.length = 2; // cắt ngắn thành 2 phần tử alert( arr ); // [1, 2] -arr.length = 5; // return length back -alert( arr[3] ); // undefined: the values do not return +arr.length = 5; // trả lại chiều dài trở lại +alert( arr[3] ); // undefined: các giá trị không trở lại ``` -So, the simplest way to clear the array is: `arr.length = 0;`. +Vì vậy, cách đơn giản nhất để xóa array là: `arr.length = 0;`. ## new Array() [#new-array] -There is one more syntax to create an array: +Còn một cú pháp nữa để tạo array: ```js -let arr = *!*new Array*/!*("Apple", "Pear", "etc"); +let arr = *!*new Array*/!*("Táo", "Lê", "v.v"); ``` -It's rarely used, because square brackets `[]` are shorter. Also there's a tricky feature with it. +Nó hiếm khi được sử dụng vì dấu ngoặc vuông `[]` ngắn hơn. Ngoài ra, còn có một tính năng phức tạp với nó. -If `new Array` is called with a single argument which is a number, then it creates an array *without items, but with the given length*. +Nếu `new Array` được gọi với một đối số duy nhất là một số, thì nó sẽ tạo một array *không có phần tử, nhưng có độ dài cho trước*. -Let's see how one can shoot themself in the foot: +Hãy xem làm thế nào một người có thể tự bắn vào chân mình: ```js run -let arr = new Array(2); // will it create an array of [2] ? +let arr = new Array(2); // nó sẽ tạo ra một array [2] ? -alert( arr[0] ); // undefined! no elements. +alert( arr[0] ); // undefined! không có yếu tố. -alert( arr.length ); // length 2 +alert( arr.length ); // độ dài 2 ``` -In the code above, `new Array(number)` has all elements `undefined`. - -To evade such surprises, we usually use square brackets, unless we really know what we're doing. +Để tránh những bất ngờ như vậy, chúng ta thường sử dụng dấu ngoặc vuông, trừ khi chúng ta thực sự biết mình đang làm gì. -## Multidimensional arrays +## Array nhiều chiều -Arrays can have items that are also arrays. We can use it for multidimensional arrays, for example to store matrices: +Array có thể có các mục cũng là array. Chúng ta có thể sử dụng nó cho array nhiều chiều, ví dụ để lưu trữ ma trận: ```js run let matrix = [ @@ -394,15 +424,14 @@ let matrix = [ [7, 8, 9] ]; -alert( matrix[1][1] ); // 5, the central element +alert( matrix[1][1] ); // 5, yếu tố trung tâm ``` ## toString -Arrays have their own implementation of `toString` method that returns a comma-separated list of elements. - -For instance: +Array có phương thức triển khai `toString` riêng để trả về danh sách các phần tử được phân tách bằng dấu phẩy. +Ví dụ: ```js run let arr = [1, 2, 3]; @@ -411,7 +440,7 @@ alert( arr ); // 1,2,3 alert( String(arr) === '1,2,3' ); // true ``` -Also, let's try this: +Ngoài ra, hãy thử điều này: ```js run alert( [] + 1 ); // "1" @@ -419,9 +448,9 @@ alert( [1] + 1 ); // "11" alert( [1,2] + 1 ); // "1,21" ``` -Arrays do not have `Symbol.toPrimitive`, neither a viable `valueOf`, they implement only `toString` conversion, so here `[]` becomes an empty string, `[1]` becomes `"1"` and `[1,2]` becomes `"1,2"`. +Array không có `Symbol.toPrimitive`, cũng không có `valueOf` khả thi, chúng chỉ chuyển đổi triển khai `toString`, vì vậy ở đây `[]` trở thành một chuỗi rỗng, `[1]` trở thành `"1"` và `[1,2]` trở thành `"1,2"`. -When the binary plus `"+"` operator adds something to a string, it converts it to a string as well, so the next step looks like this: +Khi toán tử cộng nhị phân `"+"` thêm một thứ gì đó vào một chuỗi, nó cũng chuyển đổi nó thành một chuỗi, vì vậy bước tiếp theo sẽ như sau: ```js run alert( "" + 1 ); // "1" @@ -429,31 +458,31 @@ alert( "1" + 1 ); // "11" alert( "1,2" + 1 ); // "1,21" ``` -## Don't compare arrays with == +## Đừng so sánh các array với == -Arrays in JavaScript, unlike some other programming languages, shouldn't be compared with operator `==`. +Array trong JavaScript, không giống như một số ngôn ngữ lập trình khác, không được so sánh với toán tử `==`. -This operator has no special treatment for arrays, it works with them as with any objects. +Toán tử này không có cách xử lý đặc biệt nào đối với array, nó hoạt động với chúng như với bất kỳ đối tượng nào. -Let's recall the rules: +Hãy nhớ lại các quy tắc: -- Two objects are equal `==` only if they're references to the same object. -- If one of the arguments of `==` is an object, and the other one is a primitive, then the object gets converted to primitive, as explained in the chapter . -- ...With an exception of `null` and `undefined` that equal `==` each other and nothing else. +- Hai đối tượng bằng nhau `==` chỉ khi chúng tham chiếu đến cùng một đối tượng. +- Nếu một trong các đối số của `==` là đối tượng và đối số còn lại là đối số nguyên thủy, thì đối tượng sẽ được chuyển đổi thành đối tượng nguyên hàm, như được giải thích trong chương . +- ...Ngoại trừ `null` và `undefined` bằng `==` lẫn nhau và không có gì khác. -The strict comparison `===` is even simpler, as it doesn't convert types. +So sánh nghiêm ngặt `===` thậm chí còn đơn giản hơn vì nó không chuyển đổi các loại. -So, if we compare arrays with `==`, they are never the same, unless we compare two variables that reference exactly the same array. +Vì vậy, nếu chúng ta so sánh các array bằng `==`, chúng sẽ không bao giờ giống nhau, trừ khi chúng ta so sánh hai biến tham chiếu chính xác cùng một array. -For example: +Ví dụ: ```js run alert( [] == [] ); // false alert( [0] == [0] ); // false ``` -These arrays are technically different objects. So they aren't equal. The `==` operator doesn't do item-by-item comparison. +Các array này là các đối tượng khác nhau về mặt kỹ thuật. Vì vậy, chúng không bằng nhau. Toán tử `==` không thực hiện so sánh từng mục. -Comparison with primitives may give seemingly strange results as well: +So sánh với nguyên hàm cũng có thể cho kết quả có vẻ kỳ lạ: ```js run alert( 0 == [] ); // true @@ -461,54 +490,59 @@ alert( 0 == [] ); // true alert('0' == [] ); // false ``` -Here, in both cases, we compare a primitive with an array object. So the array `[]` gets converted to primitive for the purpose of comparison and becomes an empty string `''`. +Ở đây, trong cả hai trường hợp, chúng ta so sánh một đối tượng nguyên hàm với một đối tượng array. Vì vậy, array `[]` được chuyển thành nguyên hàm cho mục đích so sánh và trở thành một chuỗi rỗng `''`. -Then the comparison process goes on with the primitives, as described in the chapter : +Sau đó, quá trình so sánh tiếp tục với các nguyên hàm, như được mô tả trong chương : ```js run -// after [] was converted to '' -alert( 0 == '' ); // true, as '' becomes converted to number 0 +// sau khi [] được chuyển đổi thành '' +alert( 0 == '' ); // khi '' được chuyển đổi thành số 0 -alert('0' == '' ); // false, no type conversion, different strings +alert('0' == '' ); // false, không chuyển đổi loại, các chuỗi khác nhau ``` -So, how to compare arrays? +Vì vậy, làm thế nào để so sánh các array? -That's simple: don't use the `==` operator. Instead, compare them item-by-item in a loop or using iteration methods explained in the next chapter. +Rất đơn giản: không sử dụng toán tử `==`. Thay vào đó, hãy so sánh từng mục của chúng trong một vòng lặp hoặc sử dụng các phương thức lặp được giải thích trong chương tiếp theo. -## Summary +## Tóm tắt -Array is a special kind of object, suited to storing and managing ordered data items. +Array là một loại đối tượng đặc biệt, phù hợp để lưu trữ và quản lý các mục dữ liệu có thứ tự. -- The declaration: +Khai báo: - ```js - // square brackets (usual) - let arr = [item1, item2...]; + ```js + // ngoặc vuông (thông thường) +let arr = [item1, item2...]; - // new Array (exceptionally rare) - let arr = new Array(item1, item2...); - ``` +// new Array (đặc biệt hiếm) +let arr = new Array(item1, item2...); +``` + +Cuộc gọi đến `new Array(number)` tạo một array có độ dài nhất định, nhưng không có phần tử. + +- Thuộc tính `length` là độ dài của array hay nói chính xác là chỉ mục cuối cùng của nó cộng với một. Nó được tự động điều chỉnh bằng các phương thức array. +- Nếu chúng ta rút ngắn `độ dài` theo cách thủ công, array sẽ bị cắt bớt. - The call to `new Array(number)` creates an array with the given length, but without elements. +Lấy các phần tử: -- The `length` property is the array length or, to be precise, its last numeric index plus one. It is auto-adjusted by array methods. -- If we shorten `length` manually, the array is truncated. +- chúng ta có thể lấy phần tử theo chỉ mục của nó, như `arr[0]` +- ngoài ra, chúng ta có thể sử dụng phương thức `at(i)` cho phép lập chỉ mục âm. Đối với các giá trị âm của `i`, nó lùi lại từ cuối array. Nếu `i >= 0`, nó hoạt động giống như `arr[i]`. -We can use an array as a deque with the following operations: +Chúng ta có thể sử dụng một array như một deque với các thao tác sau: -- `push(...items)` adds `items` to the end. -- `pop()` removes the element from the end and returns it. -- `shift()` removes the element from the beginning and returns it. -- `unshift(...items)` adds `items` to the beginning. +- `push(...items)` thêm `items` vào cuối. +- `pop()` xóa phần tử ở cuối và trả về phần tử đó. +- `shift()` loại bỏ phần tử từ đầu và trả về nó. +- `unshift(...items)` thêm `items` vào đầu. -To loop over the elements of the array: - - `for (let i=0; i`, `<` and others), as they have no special treatment for arrays. They handle them as any objects, and it's not what we usually want. +Để so sánh các array, không sử dụng toán tử `==` (cũng như `>`, `<` và các toán tử khác), vì chúng không có cách xử lý đặc biệt nào đối với array. Nó xử lý chúng như bất kỳ đối tượng nào và đó không phải là điều chúng ta thường muốn. -Instead you can use `for..of` loop to compare arrays item-by-item. +Thay vào đó, bạn có thể sử dụng vòng lặp `for..of` để so sánh từng array một. -We will continue with arrays and study more methods to add, remove, extract elements and sort arrays in the next chapter . +Chúng ta sẽ tiếp tục với array và nghiên cứu thêm các phương pháp để thêm, bớt, trích xuất các phần tử và sắp xếp array trong chương tiếp theo .