본문 바로가기

Programing/JavaScript

.slice() : 범위복사 새 배열로 반환 / .splice() : 배열삭제추가변경 / Array.prototype.push() : 배열에 요소 추가

Array.prototype.slice()

slice() 메서드는 어떤 배열의 begin부터 end까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환합니다. 

원본 배열은 수정되지 않습니다. 

배열.slice(포함시작인덱스,끝인덱스(포함x));


1
2
3
4
5
6
7
8
9
10
11
12
13
var animals = ['ant''bison''camel''duck''elephant'];
 
console.log(animals.slice(2));
// expected output: Array ["camel", "duck", "elephant"]
 
console.log(animals.slice(24));
// expected output: Array ["camel", "duck"]
 
console.log(animals.slice(15));
// expected output: Array ["bison", "camel", "duck", "elephant"]
 
console.log(animals.slice());
// expected output: Array ["ant", "bison", "camel", "duck", "elephant"]
cs


return             추출 된 요소를 포함한 새로운 배열.


Array.prototype.splice()

splice() 메서드는 배열의 기존 요소를 삭제 또는 교체 하거나 새 요소를 추가배열의 내용을 변경합니다.
배열.splice(배열인덱스, 삭제수, 배열인덱스앞에 추가될 값);

1
2
3
4
5
6
7
8
9
10
11
var months = ['Jan''March''April''June'];
months.splice(10'Feb');
// inserts at 1st index position
console.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'June']
 
months.splice(41'May');
// replaces 1 element at 4th index
console.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'May']
 
cs

return             삭제 된 요소가 포함 된 배열입니다. 요소가 하나만 제거되면 요소 하나의 배열이 반환됩니다. 
요소가 제거되지 않으면 빈 배열이 리턴됩니다.
ex ) months.splice(0,1); // return 값은  ['Jan']   (삭제된 값을 리턴)


Array.prototype.push()  /  mutable (배열이 변함)

push() 메서드는 배열의 끝에 하나 이상의 요소를 추가하고, 배열의 새로운 길이를 반환합니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
var animals = ['pigs''goats''sheep'];
 
console.log(animals.push('cows'));
// expected output: 4
 
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows"]
 
animals.push('chickens');
 
console.log(animals);
// expected output: Array ["pigs", "goats", "sheep", "cows", "chickens"]
 
cs


return             호출한 배열의 새로운 length 속성.