[JS001-002] 배열의 내장함수

고정원·2021년 6월 21일
0

1/100_JS

목록 보기
1/9
post-thumbnail

Q1. 다음 배열에서 400,500을 삭제해라

slice()

array.slice([start[,end]])
slice()메서드는 어떤 배열의 start부터 end 전 까지 얕은 복사본을 새로운 배열 객체로 반환한다.
🔥 원본 배열은 바뀌지 않는다.

📍리턴값
: 추출한 요소를 포함한 새로운 배열

let nums = [100, 200, 300, 400, 500];

//A1.1 slice - 원본배열을 수정하지 않는다.
let sliced = nums.slice(0,3);
console.log(sliced); // [100,200,300]
console.log(nums); // [100, 200, 300, 400, 500] 

splice()

array.splice(start,[, deleteCount[, item1[, item2[, ...]]]])
splice() 메서드는 배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경한다.
🔥 원본 배열은 바뀐다.
📍리턴값
: 제거한 요소를 담은 배열, 교체나 추가하고 싶은 요소들은 원본배열에 반영된다.

let nums2 = [100, 200, 300, 400, 500];

//A1.2 splice -원본배열을 수정한다.
let spliced = nums2.splice(0,3); //0부터 3 전까지의 요소를 삭제해
console.log(spliced); // [100,200,300] -삭제한 요소를 담은 배열을 리턴
console.log(nums2); // [400,500] -원본을 수정하니까 원본 nums2에는 100,200,300을 삭제한 400,500만 남아있다.

🧐삭제 뿐 아니라 교체하거나 추가하고 싶은 새 요소를 매개변수로 넣을 수 있다.
let nums3 = [100, 200, 300, 400, 500];

let nums3Change = nums3.splice(3,2,'a','b');
console.log(nums3Change); // [ 400, 500 ]
console.log(nums3); //[100,200,300, a, b]

배열의 추가,삭제,복사

const fruit = ['🍎','🍌']

//push : add an item to the end
fruit.push('🍦','🍕');
console.log(fruit); // ["🍎", "🍌", "🍦", "🍕"]

//pop : remove an item from the end
fruit.pop();
console.log(fruit);//["🍎", "🍌", "🍦"]

//unshift : add an item to the beginning
fruit.unshift();
console.log(fruit);//["🍎", "🍌", "🍦"]

//shift : remove an item from the beginning
fruit.shift();
console.log(fruit);//["🍌", "🍦"]

💡Note! shift, unshift are slower than pop, push

push, pop은 끝에 그냥 데이터 넣다뺐다 하면 되는데
shift, unshift는 제일 앞에 있던 애를 지우고, 뒤에있던애들을 하나씩 앞으로 댕겨와야하므로 전체가 움직이는꼴이되니까 오래걸림 : (

//splice : remove an item by index position 
const fruits = ['🍎','🍌']
fruits.push('🍦','🍕','🍬');
fruits.splice(1,1); //바나나만 삭제
console.log(fruits);//["🍎", "🍦", "🍕", "🍬"]

fruits.splice(2); // 피자부터 나머지 다 지움
console.log(fruits); //["🍎", "🍦"
fruits.splice(1,1,'🍟'); // 지우고 내가 넣고 싶은 감자칩을 넣을 수 있지
console.log(fruits);//["🍎", "🍟"]

//두가지의 배열 연결하기 
//concat : combine two arrays 
const fruits2 = ['🥗', '🥪'];
const newFruit = fruit.concat(fruits2);
console.log(newFruit);
profile
해결문제에 대해 즐겁게 대화 할 수 있는 프론트엔드 개발자

0개의 댓글