티스토리 뷰
Tip 5. 배열로 유연한 컬렉션을 생성하라
const team = [
'Joe',
'Dyan',
'Bea',
'Theo',
];
function alphabetizeTeam(team) {
return [...team].sort();
// ['Bea', 'Dyan', 'Joe', 'Theo']
}
=> 알파벳 순(오름차순)으로 정렬한 배열
const staff = [
{
name: 'Wesley',
position: 'musician',
},
{
name: 'Davis',
position: 'engineer',
},
];
function getMusicians(staff) {
return staff.filter(member => member.position === 'musician');
// [{name: 'Wesley', position: 'musician'}]
}
=> staff 배열 객체에서 key가 position인 것 중에 value가 'musician'인 배열 객체를 출력한다.
const game1 = {
player: 'Jim Jonas',
hits: 2,
runs: 1,
errors: 0,
};
const game2 = {
player: 'Jim Jonas',
hits: 3,
runs: 0,
errors: 1,
};
const total = {};
const stats = Object.keys(game1);
for (let i = 0; i < stats.length; i++) {
const stat = stats[i];
if (stat !== 'player') {
total[stat] = game1[stat] + game2[stat];
}
}
=> 객체를 순회하기 위한 Obkect.keys()는 객체의 키를 배열에 담은 후 생성한 배열을 이용해 순회한다.
=> 이터러블: 컬렉션의 현재 위치를 알고 있는 상태에서 컬렉션의 항목을 한 번에 하나씩 처리하는 방법.
=> map에는 내장 이터러블이 있다.
const dog = {
name: 'Don',
color: 'black',
};
dog.name;
// Don
=> dog 객체의 .key로 해당 value를 가져올 수 있다. 키-값 쌍
const dogPair = [
['name', 'Don'],
['color', 'black'],
];
function getName(dogPair) {
return dogPair.find(attribute => {
return attribute[0] === 'name';
})[1];
}
=> dogPair 객체의 요소 중 0번째가 'name'과 일치하면 'don'을 출력한다.
=> 2차원 배열.
=> 함수를 return하고 인덱스 [1]로 반환하는 value의 인덱스를 가져올 수 있다. don의 1번째인 o.
Tip 6. Includes()로 존재 여부를 확인하라
* 문자열의 색인이 0일 경우 0은 false 거짓으로 평가될 수 있다.
const sections = ['shipping'];
function displayShipping(sections) {
if (sections.indexOf('shipping')) {
return true;
}
return false;
}
=> 올바른 문자열이 있음에도 불구하고 index가 0이므로 false가 반환되고 있다.
const sections = ['contact', 'shipping'];
function displayShipping(sections) {
return sections.indexOf('shipping') > -1;
}
=> 이렇게 index를 비교하는 과정이 있어야 올바른 값을 반환할 수 있다.
const sections = ['contact', 'shipping'];
function displayShipping(sections) {
return sections.includes('shipping');
}
=> -1과 비교하는 과정의 코드를 여러번 반복하지 않고도 includes 메서드를 사용하여 올바른 값을 반환할 수 있다.
'JS' 카테고리의 다른 글
3장 특수한 컬렉션을 이용해 코드 명료성을 극대화하라 (10~12) (3) | 2023.11.12 |
---|---|
2장 배열로 데이터 컬렉션을 관리하라 (Tip7-9) (2) | 2023.10.29 |
1장 변수 할당으로 의도를 표현하라 (0) | 2023.10.21 |
1장 변수 할당으로 의도를 표현하라 (0) | 2023.10.08 |
JS - splice() (1) | 2023.08.04 |