9강 문제 따라해보기!
const fruits = [`apple`, 'banana', 'orange'];
# what I did
for (let fruit of fruits) {
console.log(fruit);
console.log(`${fruit} + ${fruit} + ${fruit}`);
}
//출력값
//apple
//apple + apple + apple
//banana
//banana + banana + banana
//orange
//orange + orange + orange
-> 나의 의도는 배열 안의 요소를 하나씩 꺼내서 이어붙이는 것이었다. 하지만 대실패!! 와후😎 MND에 검색하지 않았던 나에게 박수를 보낸다~
# what Ellie did
const result = fruits.join(`, `);apple, banana, orange
console.log(result);
.join([separator]) : 배열의 모든 요소를 연결하여 하나의 문자열로 변환
separator
☆
각 요소를 구분할 문자열을 지정한다. 생략 시 요소들은 쉼표로 구분하고, 빈 문자열이라면 띄어쓰기 없이 연결된다.
const fruit = '사과, 배, 당근, 키위';
# what I did
const arr = fruit.split();//["사과, 배, 당근, 키위"]
console.log(arr);
-> seperator를 쓰지 않아서 array 안에 하나의 string으로 담겼다.
#what Ellie did
const array = fruits.split(',', 3); //["사과", " 배", " 당근"]
console.log(array);
.split([separator[, limit]]) : String을 (여러 개의 문자열로 나누어) array 안으로 넣는다.
separator
☆
끊어야 할 부분을 지정할 수 있다. 생략 시 문자열이 하나의 요소로 배열안으로 들어간다. 또한''
일 경우, 문자 단위로 변환된다.limit
☆
불러올 문자열의 개수를 나타낸다. 남아있는 문자들을 출력되지 않는다.
const array = [1, 2, 3, 4, 5];
# what I did
const reverseArr = array.reverse();
console.log(reverseArr); // 54321
console.log(array);//54321
-> 원형에 변화가 생긴다. 원래 값의 변화가 없길 바란다면
slice
를 사용하자!const newArr = array.slice().reverse(); console.log(newArr);//54321 console.log(array);//12345
const array = ['👿', '👿', '😈', '😈', '😈'];
# what I did
const result = array.splice(2);
console.log(result);
console.log(array);// 원래값이 수정된 것을 확인할 수 있음
-> splice와 slice에 대한 개념이 혼동되어있었다. index 2 부터 끝까지의 내용을 새로 불러오려했는데 원래 값에서 😈 😈 😈를 잘라버렸다..!
# what Ellie did
const result = array.slice(2);
console.log(result);
console.log(array);
.splice(start[, deleteCount[, item1[, item2[, ...]]]]) : 배열의 기존 요소를 삭제 또는 교체하거나 새 요소를 추가하여 배열의 내용을 변경
start
★
배열의 변경을 시작할 인덱스
음수인 경우 인덱스 순서를 reverse한다. (-1이라면 끝에서 두 번째부터 시작)deleteCount
☆
배열에서 제거할 요소의 수
생략할 시 start부터의 모든 요소 제거item1, item2, ...
☆
배열에 추가할 요소
slice(beginIndex[, endIndex]) : 문자열의 부분을 복사
beginIndex
★
추출 시작점인 0부터 시작하는 인덱스endIndex
☆
종료지점. 해당 인덱스 직전까지 추출한다!
-> splice가 일부를 자르거나 요소들을 교체한다면, slice는 일부를 새로 복사하는 느낌!!(slice;원래 값에 영향을 주지 않는다!)