🟨 JavaScript/개념
[드림코딩] 유용한 배열(array) api (1) : join, split, reverse, slice, find
Zoeeey
2022. 6. 7. 12:40
join
배열의 모든 데이터를 string으로 합쳐 변환한다.
const goodcoders = ['noran', 'paran', 'black', 'white'];
const result = goodcoders.join();
console.log(result);
//noran,paran,black,white
참고 아래처럼 구분자를 전달하면 전달된 구분자로 구분되어 나타난다.
const result = goodcoders.join(|);
console.log(result);
//noran|paran|black|white
split
string 데이터를 배열로 만든다.
const coders = 'noran,paran,black,white';
const result = coders.split(',');
console.log(result);
// [object Array] (4)
// ["noran","paran","black","white"]
주의 split()을 비워두면 배열이 나뉘지 않고 통째로 한개의 데이터를 가진 배열이 된다.
const coders = 'noran,paran,black,white';
const result = coders.split();
console.log(result);
// [object Array] (1)
// ["noran,paran,black,white"]
참고 split()뒤에 숫자를 넣으면 앞에서부터 몇개의 데이터만 전달받을지 limit을 걸 수 있다.
const coders = 'noran,paran,black,white';
const result = coders.split(',', 2);
console.log(result);
// [object Array] (2)
// ["noran","paran"]
reverse
배열을 거꾸로 바꾼다.
const coders = ["noran","paran","black","white"];
const result = coders.reverse();
console.log(result);
// [object Array] (4)
// ["white","black","paran","noran"]
* 주의 : reverse를 쓰면 return된 result 뿐 아니라 원래 배열인 coders 자체도 순서가 바뀐다.
slice
원래의 배열에서 원하는 부분만 return해서 받아 새로운 배열을 만든다.
slice(몇번째의 데이터부터 가져올지, 몇번째의 데이터까지 가져올지)
여기서 뒤에 붙는 숫자는 exclusive하다. (이것은 빠지고 가져온다) 그렇기 때문에 0-4까지의 배열의 경우 4까지 가져오고 싶다면 뒤의 숫자를 5로 붙이면 된다.
const coders = [0,1,2,3,4];
const result = coders.slice(2, 4);
console.log(result);
// [object Array] (2)
// [2,3]
splice와 다른 점
- splice는 원래의 배열이 수정이 된다.
- slice는 return된 값으로 새로운 배열을 만든다.
find
class Coder {
constructor(name, age, enrolled, score) {
this.name = name;
this.age = age;
this.enrolled = enrolled;
this.score = score;
}
}
const coders = [
new Coder('A', 29, true, 45),
new Coder('B', 28, false, 80),
new Coder('C', 30, true, 90),
new Coder('D', 40, false, 66),
new Coder('E', 18, true, 88),
]
score이 90인 coder를 찾아보자.
const result = coders.find(function (coder, index) {
return coder.score === 90;
});
console.clear();
console.log(result);
// [object Object]
// {
// "name": "C",
// "age": 30,
// "enrolled": true,
// "score": 90
// }
위 콜백함수를 화살표함수로 변환하자. (index도 쓰지 않으니 빠진다)
const result = coders.find((coder) => coder.score === 90);
* 참고 : find는 가장 먼저 찾은 데이터를 return하고 종료한다.
출처 : 드림코딩 https://www.youtube.com/@dream-coding / MDN https://developer.mozilla.org/ko