04 Arrays 배열
1. 배열 작성 시 리터럴 구문 사용
const arr = [];
2. 배열 인덱스를 통해 항목 대입하는 것을 지양하고, Array.prototype.push() 를 이용할 것
const stacking = [];
//bad
stacking[stacking.length] = 'pushThing';
//good
stacking.push('pushThing');
3. 배열 복사할 때 spreads( ... , 확장 연산자) 사용
const items = [0,1,2,'three',4,'end'];
//Bad
const len = items.length;
const itemCopy = [];
for(let i=0; i<len ; i++){
itemCopy[i] = items[i];
}
//Good
const itemCopy = [...items];
4. 유사배열객체를 배열로 반환하려면, Array객체의 정적메서드 Array.from() 을 사용하자.
//class가 foo인 요소들을 수집한 array-like object (HTMLCollection)
const foo = document.querySelectorAll('.foo');
const fooNodes = Array.from(foo);
05 Destructuring 디스트럭처링 (구조화대입 - 구조 분해, 할당)
1. Array Destructuring
const arr = [1,2,3,4,5];
const [first, second] = arr;
//const first = 1;
//const second = 2;
2. Object Destructuring 하나의 오브젝트에서 복수의 프로퍼티에 access할 때 오브젝트 구조화 대입을 사용한다.
✎ How to apply 1 : 하나의 오브젝트에서 복수의 프로퍼티에 접근할 때 필요
const user = {
firstName : 'Lee',
lastName : 'chanhyuk'
};
//bad
function getFullName(user){
const firstName = user.firstName;
const lastName = user.lastName;
return `${firstName} ${lastName}`;
}
//better
function getFullName(user){
const {firstName, lastName} = user; //Object Destructuring
return `${firstName} ${lastName}`;
}
//good
function getFullName({firstName, lastName}){
return `${firstName} ${lastName}`; //Object Destructuring
}
✎ How to apply 2 : 배열은 순서에 따라 가져오지만 오브젝트는 프로퍼티명에 따라 가져온다. 배열 디스트럭처링과 비교해보자
const input = {
left: 10,
right: 0,
top: 20,
bottom: 30
};
const {left, bottom} = input;
//left = 10;
//bottom = 30;
같은 변수 할당을 array destructuring 으로 할 수 있다. 하지만 변수의 순서를 고려해야 하므로, 번거로운 작업임을 확인해보자.
const input = [10,0,20,30];
const [left,,,bottom] = input;
//left = 10;
//bottom = 30;
✎ How to apply 3 : 오브젝트 프로퍼티명을 바꾸어 변수에 할당해주고 싶다면 : 을 이용하자.
const / let { 오브젝트의 프로퍼티명 : 새롭게 정의할 변수} = 할당할 값이 들어있는 오브젝트 ;
const suzi = {
name: 'suzi',
age: 21
};
const {name: suziName, age: suziAge} = suzi;
//suziName 변수의 값은 'suzi'
//suziAge 변수의 값은 21
06 Strings
1. 문자열에는 single quote ('') 사용이 권장됨
2. 100문자 이상의 문자열은 문자열 연결을 이용하여 표현한다.
3. 문자 연결 과용은 성능저하를 야기한다.
4. 프로그램에서 문자열 생성 시 템플릿template (`backtick) 사용할 것
5. eval() 은 사용 금지: 전역객체의 함수속성 eval('string')
'JavaScript > 스타일가이드 정리하기' 카테고리의 다른 글
스타일 가이드 복습하기 03 (Functions, ArrowFunctions) (0) | 2023.08.22 |
---|---|
스타일가이드 복습하기 01 (Types, References, Objects) (0) | 2023.08.22 |