slice() 메서드는 어떤 배열의 begin부터 end까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환합니다. 원본 배열은 수정되지 않습니다.
The source for this interactive demo is stored in a GitHub repository. If you'd like to contribute to the interactive demo project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
구문
arr.slice([begin[, end]])
매개변수
beginOptional- 0을 시작으로 하는 추출 시작점에 대한 인덱스를 의미합니다.
- 음수 인덱스는 배열의 끝에서부터의 길이를 나타냅니다.
slice(-2)는 배열에서 마지막 두 개의 엘리먼트를 추출합니다. begin이 undefined인 경우에는, 0번 인덱스부터slice합니다.begin이 배열의 길이보다 큰 경우에는, 빈 배열을 반환합니다.endOptional- 추출을 종료 할 0 기준 인덱스입니다.
slice는end인덱스를 제외하고 추출합니다. - 예를들어,
slice(1,4)는 두번째 요소부터 네번째 요소까지 (1, 2 및 3을 인덱스로 하는 요소) 추출합니다. - 음수 인덱스는 배열의 끝에서부터의 길이를 나타냅니다. 예를들어
slice(2,-1)는 세번째부터 끝에서 두번째 요소까지 추출합니다. end가 생략되면slice는 배열의 끝까지(arr.length) 추출합니다.
만약 end값이 배열의 길이보다 크다면, silce는 배열의 끝까지(arr.length) 추출합니다.
-
반환 값
추출한 요소를 포함한 새로운 배열.
설명
slice는 원본을 대체하지 않습니다. 원본 배열에서 요소의 얕은 복사본을 반환합니다. 원본 배열의 요소는 다음과 같이 반환 된 배열에 복사됩니다:
- 객체 참조 (및 실제 객체가 아님)의 경우,
slice는 객체 참조를 새 배열로 복사합니다. 원본 배열과 새 배열은 모두 동일한 객체를 참조합니다. 참조 된 객체가 변경되면 변경 내용은 새 배열과 원래 배열 모두에서 볼 수 있습니다. String및Number객체가 아닌 문자열과 숫자의 경우slice는 문자열과 숫자를 새 배열에 복사합니다. 한 배열에서 문자열이나 숫자를 변경해도 다른 배열에는 영향을 주지 않습니다.
새 요소가 두 배열 중 하나에 추가되면 다른 배열은 영향을 받지 않습니다.
예제
기존 배열의 일부 반환
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']; var citrus = fruits.slice(1, 3); // fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'] // citrus contains ['Orange','Lemon']
slice 사용하기
다음 예제에서 slice는 myCar에서 newCar라는 새 배열을 만듭니다. 두 가지 모두 myHonda 객체에 대한 참조를 포함합니다. myHonda의 색상이 자주색으로 변경되면 두 배열 모두 변경 사항을 반영합니다.
// 슬라이스를 사용하여 내 차에서 새 차를 만듭니다.
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);
// 내 자동차, 새 자동차 및 혼다의 색상 값을 표시합니다.
// 두 배열에서 모두 참조됩니다.
console.log('myCar = ' + myCar.toSource());
console.log('newCar = ' + newCar.toSource());
console.log('myCar[0].color = ' + myCar[0].color);
console.log('newCar[0].color = ' + newCar[0].color);
// myHonda의 색상을 변경합니다.
myHonda.color = 'purple';
console.log('The new color of my Honda is ' + myHonda.color);
// 두 배열에서 참조 된 myHonda의 색상을 표시합니다.
console.log('myCar[0].color = ' + myCar[0].color);
console.log('newCar[0].color = ' + newCar[0].color);
이 스크립트는 다음과 같이 씁니다.
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
배열형 객체
slice 메서드를 호출하여 Array와 유사한 객체 / 컬렉션을 새 Array로 변환 할 수도 있습니다. 메서드를 객체에 바인딩하면됩니다. 함수 안에있는 arguments는 'array-like object'의 예입니다.
function list() {
return Array.prototype.slice.call(arguments);
}
var list1 = list(1, 2, 3); // [1, 2, 3]
바인딩은 Function.prototype의 .call 함수를 사용하여 수행 할 수 있으며 Array.prototype.slice.call 대신 [] .slice.call (arguments)을 사용하여 줄일 수도 있습니다. 어쨌든, 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]
크로스 브라우저 동작 간소화
DOM 객체와 같은 호스트 객체는 Spec에 의해 Array.prototype.slice로 변환 할 때 Mozilla 동작을 따르지 않아도되지만 IE <9는 그렇지 않습니다. 버전 9로 시작하는 IE 버전에서는이를 허용하고 "shimming" 그것은 신뢰할 수있는 크로스 브라우저 동작을 허용 할 수 있습니다. 현재 다른 브라우저가 IE, Mozilla, Chrome, Safari 및 Opera처럼이 기능을 계속 지원하는 한이 심에 의존하는 (DOM을 지원하는) 슬라이스 코드를 읽는 개발자는 의미에 잘못 인도되지 않습니다. 그들은 사실상 사실상 표준 행동을 제공하기 위해 의미에 의존 할 수 있습니다. (심은 IE가 이전 버전의 IE에서도 허용하지 않았던 null / undefined 값 인 slice ()의 두 번째 인수와 함께 작동하도록 IE를 수정합니다. IE> = 9를 포함한 모든 최신 브라우저는 현재 수행합니다.)
/ **
* 슬라이스를 적용하기위한 IE의 "지원"부족 (IE <9)을 "고정"하기위한 것
* NamedNodeMap, NodeList 및 HTMLCollection과 같은 호스트 객체에서
* (기술적으로, 호스트 객체는 구현에 의존하기 때문에,
* 적어도 ES6 이전에는 IE가 이러한 방식으로 작동하지 않아도되었습니다.)
* 또한 문자열에서 작동하며 IE <9를 수정하여 명시 적으로 정의되지 않도록합니다.
* (Firefox에서와 같이) 두 번째 인수에 대해
* 다른 DOM 객체에서 호출되었습니다.
* /
(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
// 이것은 진짜 배열, 배열과 같은 객체,
// NamedNodeMap (속성, 엔티티, 표기법),
// NodeList (예 : getElementsByTagName), HTMLCollection (예 : childNodes),
// 그리고 다른 DOM 객체에서는 실패하지 않습니다 (IE <9에서 DOM 요소처럼)
Array.prototype.slice = function(begin, end) {
// 정의되지 않은 끝 인자로 IE <9가 불만해진다.
end = (typeof end !== 'undefined') ? end : this.length;
// 네이티브 Array 객체의 경우 네이티브 slice 함수를 사용합니다.
if (Object.prototype.toString.call(this) === '[object Array]'){
return _slice.call(this, begin, end);
}
// object와 같은 배열을 위해 우리는 스스로 처리한다.
var i, cloned = [],
size, len = this.length;
// "begin"에 대한 음수 값을 처리합니다.
var start = begin || 0;
start = (start >= 0) ? start : Math.max(0, len + start);
// "end"에 대한 음수 값을 처리합니다.
var upTo = (typeof end == 'number') ? Math.min(end, len) : len;
if (end < 0) {
upTo = len + end;
}
// 슬라이스의 실제 예상 크기
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;
};
}
}());
명세
| Specification | Status | Comment |
|---|---|---|
| ECMAScript 3rd Edition (ECMA-262) | Standard | Initial definition. Implemented in JavaScript 1.2. |
| ECMAScript 5.1 (ECMA-262) The definition of 'Array.prototype.slice' in that specification. |
Standard | |
| ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'Array.prototype.slice' in that specification. |
Standard | |
| ECMAScript Latest Draft (ECMA-262) The definition of 'Array.prototype.slice' in that specification. |
Draft |
브라우저 호환성
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
slice | Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support Yes | Opera Full support Yes | Safari Full support Yes | WebView Android Full support Yes | Chrome Android Full support Yes | Firefox Android Full support 4 | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support Yes | nodejs Full support Yes |
Legend
- Full support
- Full support