aboutsummaryrefslogtreecommitdiff
path: root/files/vi/web/javascript/reference/global_objects/array/slice/index.html
blob: ee7fd818905a57ff72cdc95f2e00e29d9b0bfd83 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
---
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
---
<div>{{JSRef}}</div>

<p>Phương thức <code><strong>slice()</strong></code> 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ừ <code>begin</code> dến <code>end</code> (không bao gồm <code>end</code>). Mảng ban đầu không bị thay đổi.</p>

<div>{{EmbedInteractiveExample("pages/js/array-slice.html")}}</div>

<p class="hidden">Mã nguồn của đoạn demo này được lưu ở một repository trên Github. Bạn có thể giúp đỡ cho dự án này bằng cách clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> và gửi pull request cho chúng tôi.</p>

<h2 id="Cú_pháp">Cú pháp</h2>

<pre class="syntaxbox"><var>arr</var>.slice()
<var>arr</var>.slice(<em>begin</em>)
<var>arr</var>.slice(<var>begin</var>, <var>end</var>)
</pre>

<h3 id="Tham_số">Tham số</h3>

<dl>
 <dt><code>begin</code> {{optional_inline}}</dt>
 <dd>Chỉ số bắt đầu chọn phần tử từ phần tử 0.</dd>
 <dd>Nếu chỉ số này là số âm, được xem như tính ngược từ cuối của mảng. <code>slice(-2)</code> chọn hai phần tử cuối cùng của mảng.</dd>
 <dd>Nếu <code>begin</code> là không xác định (undefined), <code>slice</code> bắt đầu từ chỉ số <code>0</code>.</dd>
</dl>

<p>     Nếu begin lớn hơn độ dài của mảng, một mảng trống được trả về.</p>

<dl>
 <dt><code>end</code> {{optional_inline}}</dt>
 <dd>Chỉ số ngừng chọn phần tử. <code>slice</code> chọn ra các phần tử có chỉ số trước chỉ số <code>end</code>.</dd>
 <dd>Ví dụ, <code>slice(1,4)</code> chọn phần thử thứ hai, thứ ba và thứ tư (ở các chỉ số 1, 2, và 3).</dd>
 <dd>Chỉ số âm tính ngược từ cuối mảng về. <code>slice(2,-1)</code> 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.</dd>
 <dd>Nếu tham số <code>end</code> không được truyền vào, <code>slice</code> chọn đến cuối mảng (<code>arr.length</code>)<code>.</code></dd>
 <dd>Nếu <code>end</code> lớn hơn độ dài mảng, <code>slice</code> chỉ chọn đến cuối mảng (<code>arr.length</code>).</dd>
</dl>

<h3 id="Gia_trị_trả_về">Gia trị trả về</h3>

<p>Một mảng mới chứa các phần tử được chọn.</p>

<h2 id="Mô_tả">Mô tả</h2>

<p><code>slice</code> 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:</p>

<ul>
 <li>Đối với tham chiếu đối tượng, <code>slice</code> sao chép tham chiếu của đối tượng vào mảng mới. Cả mảng ban đầu và mảng mới trả về đều tham chiếu tới chung đối tượng. Nếu đối tượng được tham chiếu thay đổi, cả hai mảng đều nhận sự thay đổi này.</li>
 <li>Đối với giá trị kiểu chuỗi, số và bool, (không phải các đối tượng kiểu {{jsxref("String")}}, {{jsxref("Number")}} và {{jsxref("Boolean")}} ), <code>slice</code> sao chép các giá trị vào mảng mới. Những thay đổi đối với các giá trị kiểu chuỗi, số và bool ở mảng này không còn ảnh hưởng tới mảng kia.</li>
</ul>

<p>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.</p>

<h2 id="Ví_dụ">Ví dụ</h2>

<h3 id="Trả_về_mảng_con_của_một_mảng">Trả về mảng con của một mảng </h3>

<pre class="brush: js">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']
</pre>

<h3 id="Sử_dụng_slice">Sử dụng <code>slice</code></h3>

<p>Trong ví dụ sau, <code>slice</code> tạo một mảng mới, <code>newCar</code>, từ <code>myCar</code>. Cả hai chứa tham chiếu tới đối tượng <code>myHonda</code>. Khi trường color của đối tượng <code>myHonda</code> đổi sang purple, cả hai mảng đều thấy sự thay đổi này.</p>

<pre class="brush: js">// 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);
</pre>

<p>Đoạn mã trên in ra:</p>

<pre class="brush: js">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
</pre>

<h2 id="Các_đối_tượng_giống_kiểu_mảng">Các đối tượng giống kiểu mảng</h2>

<p><code>slice</code> 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.</p>

<pre class="brush: js">function list() {
  return Array.prototype.slice.call(arguments);
}

var list1 = list(1, 2, 3); // [1, 2, 3]
</pre>

<p>Để sử dụng phương thức này, sử dụng phương thức.<code>call</code>  {{jsxref("Function.prototype")}} để gọi <code>[].slice.call(arguments)</code> thay vì <code>Array.prototype.slice.call</code>. Hoặc đơn giản hơn là {{jsxref("Function.prototype.bind", "bind")}}.</p>

<pre class="brush: js">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]
</pre>

<h2 id="Sử_dụng_trên_nhiều_trình_duyệt">Sử dụng trên nhiều trình duyệt</h2>

<p>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  <code>Array.prototype.slice</code> và IE &lt; 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 <code>slice()</code> để 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 &gt;= 9.)</p>

<pre class="brush: js">/**
 * Shim for "fixing" IE's lack of support (IE &lt; 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 &lt; 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 &lt; 9
    _slice.call(document.documentElement);
  } catch (e) { // Fails in IE &lt; 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 &lt; 9)
    Array.prototype.slice = function(begin, end) {
      // IE &lt; 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 &gt;= 0) ? start : Math.max(0, len + start);

      // Handle negative value for "end"
      var upTo = (typeof end == 'number') ? Math.min(end, len) : len;
      if (end &lt; 0) {
        upTo = len + end;
      }

      // Actual expected size of the slice
      size = upTo - start;

      if (size &gt; 0) {
        cloned = new Array(size);
        if (this.charAt) {
          for (i = 0; i &lt; size; i++) {
            cloned[i] = this.charAt(start + i);
          }
        } else {
          for (i = 0; i &lt; size; i++) {
            cloned[i] = this[start + i];
          }
        }
      }

      return cloned;
    };
  }
}());
</pre>

<h2 id="Đặc_tả">Đặc tả</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Đặc tả</th>
   <th scope="col">Trạng thái</th>
   <th scope="col">Bình luận</th>
  </tr>
  <tr>
   <td>{{SpecName('ES3')}}</td>
   <td>{{Spec2('ES3')}}</td>
   <td>Định nghĩa ban đầu. Xuất hiện ở Javascript 1.2.</td>
  </tr>
  <tr>
   <td>{{SpecName('ES5.1', '#sec-15.4.4.10', 'Array.prototype.slice')}}</td>
   <td>{{Spec2('ES5.1')}}</td>
   <td></td>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-array.prototype.slice', 'Array.prototype.slice')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td></td>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-array.prototype.slice', 'Array.prototype.slice')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td></td>
  </tr>
 </tbody>
</table>

<h2 id="Độ_tương_thích_với_trình_duyệt">Độ tương thích với trình duyệt</h2>

<div>
<div class="hidden">Bảng độ tương thích trong trang này được tạo ra từ dữ liệu có cấu trúc. Nếu bạn muốn đóng góp cho dữ liệu này, hãy gửi một cho chúng tôi một pull request đến github <a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a></div>

<p>{{Compat("javascript.builtins.Array.slice")}}</p>
</div>

<h2 id="Xem_thêm">Xem thêm</h2>

<ul>
 <li>{{jsxref("Array.prototype.splice()")}}</li>
 <li>{{jsxref("Function.prototype.call()")}}</li>
 <li>{{jsxref("Function.prototype.bind()")}}</li>
</ul>