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(2, 4)); // expected output: Array ["camel", "duck"] console.log(animals.slice(1, 5)); // 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(1, 0, 'Feb'); // inserts at 1st index position console.log(months); // expected output: Array ['Jan', 'Feb', 'March', 'April', 'June'] months.splice(4, 1, '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 속성.
'Programing > JavaScript' 카테고리의 다른 글
Double Exclamation Mark(느낌표 두개) (0) | 2019.01.23 |
---|---|
for...in 문 // 객체에서 중복된 값을 제외하고 객체 추가하기 (0) | 2019.01.22 |
.concat() // 배열, 문자열 합치기 (0) | 2019.01.21 |
.split() / 문자열을 배열로 분할, .split() 으로 특정문자개수 반환하기 (0) | 2019.01.21 |
.shift() .pop() / 배열에서 요소제거 (0) | 2019.01.21 |