JavaScript 배열 스플 라이스 및 슬라이스
차이점은 무엇이며 splice
그리고 slice
?
$scope.participantForms.splice(index, 1);
$scope.participantForms.slice(index, 1);
splice()
원래 배열을 변경하지만 slice()
그렇지 않으면 둘 다 배열 객체를 반환합니다.
아래 예를 참조하십시오.
var array=[1,2,3,4,5];
console.log(array.splice(2));
이 반환 [3,4,5]
됩니다. 원래 어레이 영향 의 결과로 array
존재 [1,2]
.
var array=[1,2,3,4,5]
console.log(array.slice(2));
이 반환 [3,4,5]
됩니다. 원의 배열은 영향을받지 않는 결과로 array
되 [1,2,3,4,5]
.
아래는 이것을 확인하는 간단한 바이올린입니다.
//splice
var array=[1,2,3,4,5];
console.log(array.splice(2));
//slice
var array2=[1,2,3,4,5]
console.log(array2.slice(2));
console.log("----after-----");
console.log(array);
console.log(array2);
스플 라이스와 슬라이스는 모두 자바 스크립트 배열 함수입니다.
스플 라이스 대 슬라이스
splice () 메서드는 배열에서 제거 된 항목을 반환하고 slice () 메서드는 배열에서 선택한 요소를 새 배열 객체로 반환합니다.
splice () 메서드는 원래 배열을 변경하고 slice () 메서드는 원래 배열을 변경하지 않습니다.
splice () 메서드는 n 개의 인수를 사용할 수 있으며 slice () 메서드는 2 개의 인수를 사용합니다.
예제가있는 스플 라이스
인수 1 : 색인, 필수 항목을 추가 / 제거 할 위치를 지정하는 정수입니다. 음수 값을 사용하여 배열 끝에서 위치를 지정하십시오.
인수 2 : 선택 사항. 제거 할 항목 수입니다. 0으로 설정하면 항목이 제거되지 않습니다. 전달하지 않으면 제공된 색인의 모든 항목이 제거됩니다.
인수 3… n : 선택 사항. 배열에 추가 할 새 항목
var array=[1,2,3,4,5];
console.log(array.splice(2));
// shows [3, 4, 5], returned removed item(s) as a new array object.
console.log(array);
// shows [1, 2], original array altered.
var array2=[6,7,8,9,0];
console.log(array2.splice(2,1));
// shows [8]
console.log(array2.splice(2,0));
//shows [] , as no item(s) removed.
console.log(array2);
// shows [6,7,9,0]
예를 들어 슬라이스
인수 1 : 필수입니다. 선택을 시작할 위치를 지정하는 정수입니다 (첫 번째 요소의 색인은 0입니다). 배열의 끝에서 선택하려면 음수를 사용하십시오.
인수 2 : 선택 사항. 선택을 종료 할 위치를 지정하지만 포함하지 않는 정수입니다. 생략하면 시작 위치에서 배열 끝까지의 모든 요소가 선택됩니다. 배열의 끝에서 선택하려면 음수를 사용하십시오.
var array=[1,2,3,4,5]
console.log(array.slice(2));
// shows [3, 4, 5], returned selected element(s).
console.log(array.slice(-2));
// shows [4, 5], returned selected element(s).
console.log(array);
// shows [1, 2, 3, 4, 5], original array remains intact.
var array2=[6,7,8,9,0];
console.log(array2.slice(2,4));
// shows [8, 9]
console.log(array2.slice(-2,4));
// shows [9]
console.log(array2.slice(-3,-1));
// shows [8, 9]
console.log(array2);
// shows [6, 7, 8, 9, 0]
슬라이스 () 메소드는 새로운 어레이 오브젝트에 배열의 일부의 사본을 돌려 준다.
$scope.participantForms.slice(index, 1);
이것은 않습니다 NOT 변경 participantForms
배열을 만에서 발견 된 하나의 요소가 포함 된 새로운 배열을 반환 index
원래의 배열의 위치를.
접합부 () 메소드는 기존의 요소를 제거 및 / 또는 새로운 구성 요소를 추가하여 배열의 내용을 변경한다.
$scope.participantForms.splice(index, 1);
그러면 위치 participantForms
에서 한 요소가 배열에서 제거됩니다 index
.
이것들은 Javascript 네이티브 함수이며 AngularJS는 그들과 관련이 없습니다.
여기의 차이 기억하는 간단한 트릭 slice
대이splice
var a=['j','u','r','g','e','n'];
// array.slice(startIndex, endIndex)
a.slice(2,3);
// => ["r"]
//array.splice(startIndex, deleteCount)
a.splice(2,3);
// => ["r","g","e"]
Trick to remember:
"spl" (first 3 letters of splice)
두 번째 인수는 색인이 아닌 길이 여야한다는 "특정 길이"에 대해 짧게 생각하십시오.
스플 라이스 - MDN 참조 - ECMA-262 사양
통사론
array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
매개 변수
start
: 필수. 초기 색인.
경우start
가 취급되는 마이너스"Math.max((array.length + start), 0)"
의 단부에서 유효 사양 (아래에 제공된 예) 당array
.deleteCount
: 선택 사항. 제거 할 요소 수입니다 (start
제공되지 않은 경우 모두 ).item1, item2, ...
: 선택 사항.start
인덱스 에서 배열에 추가 할 요소
반환 된 요소가있는 배열 (제거되지 않은 경우 빈 배열)
Mutate original array: Yes
Examples:
const array = [1,2,3,4,5];
// Remove first element
console.log('Elements deleted:', array.splice(0, 1), 'mutated array:', array);
// Elements deleted: [ 1 ] mutated array: [ 2, 3, 4, 5 ]
// array = [ 2, 3, 4, 5]
// Remove last element (start -> array.length+start = 3)
console.log('Elements deleted:', array.splice(-1, 1), 'mutated array:', array);
// Elements deleted: [ 5 ] mutated array: [ 2, 3, 4 ]
More examples in MDN Splice examples
Slice - MDN reference - ECMA-262 spec
Syntax
array.slice([begin[, end]])
Parameters
begin
: optional. Initial index (default 0).
Ifbegin
is negative it is treated as"Math.max((array.length + begin), 0)"
as per spec (example provided below) effectively from the end ofarray
.end
: optional. Last index for extraction but not including (default array.length). Ifend
is negative it is treated as"Math.max((array.length + begin),0)"
as per spec (example provided below) effectively from the end ofarray
.
Returns: An array containing the extracted elements.
Mutate original: No
Examples:
const array = [1,2,3,4,5];
// Extract first element
console.log('Elements extracted:', array.slice(0, 1), 'array:', array);
// Elements extracted: [ 1 ] array: [ 1, 2, 3, 4, 5 ]
// Extract last element (start -> array.length+start = 4)
console.log('Elements extracted:', array.slice(-1), 'array:', array);
// Elements extracted: [ 5 ] array: [ 1, 2, 3, 4, 5 ]
More examples in MDN Slice examples
Performance comparison
Don't take this as absolute truth as depending on each scenario one might be performant than the other.
Performance test
Splice and Slice are built-in Javascript commands -- not specifically AngularJS commands. Slice returns array elements from the "start" up until just before the "end" specifiers. Splice mutates the actual array, and starts at the "start" and keeps the number of elements specified. Google has plenty of info on this, just search.
splice & delete Array item by index
index = 2
//splice & will modify the origin array
const arr1 = [1,2,3,4,5];
//slice & won't modify the origin array
const arr2 = [1,2,3,4,5]
console.log("----before-----");
console.log(arr1.splice(2, 1));
console.log(arr2.slice(2, 1));
console.log("----after-----");
console.log(arr1);
console.log(arr2);
let log = console.log;
//splice & will modify the origin array
const arr1 = [1,2,3,4,5];
//slice & won't modify the origin array
const arr2 = [1,2,3,4,5]
log("----before-----");
log(arr1.splice(2, 1));
log(arr2.slice(2, 1));
log("----after-----");
log(arr1);
log(arr2);
//splice
var array=[1,2,3,4,5];
console.log(array.splice(2));
//slice
var array2=[1,2,3,4,5]
console.log(array2.slice(2));
console.log("----after-----");
console.log(array);
console.log(array2);
JavaScript Array splice() Method By Example
Example1 by tutsmake -Remove 2 elements from index 2
var arr = [ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" ];
arr.splice(1,2);
console.log( arr );
Example-2 By tutsmake – Add new element from index 0 JavaScript
var arr = [ "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten" ];
arr.splice(0,0,"zero");
console.log( arr );
Example-3 by tutsmake – Add and Remove Elements in Array JavaScript
var months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb'); // add at index 1
console.log(months);
months.splice(4, 1, 'May'); // replaces 1 element at index 4
console.log(months);
https://www.tutsmake.com/javascript-array-splice-method-by-example/
Another example:
[2,4,8].splice(1, 2) -> returns [4, 8], original array is [2]
[2,4,8].slice(1, 2) -> returns 4, original array is [2,4,8]
참고URL : https://stackoverflow.com/questions/37601282/javascript-array-splice-vs-slice
'program tip' 카테고리의 다른 글
부울을 기준으로 AngularJS에서 ng-show를 어떻게 전환합니까? (0) | 2020.07.28 |
---|---|
파일 이름에 타임 스탬프 추가 (0) | 2020.07.28 |
자바 스크립트에서 기기 너비를 가져옵니다. (0) | 2020.07.28 |
업로드하기 전에 이미지 미리보기 표시 (0) | 2020.07.28 |
std :: swap ()을 오버로드하는 방법 (0) | 2020.07.28 |