--- 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ái Bì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