형 변환(type casting)
- 개발자의 의도와는 상관없이 표현식을 평가하는 도중에 엔진에 의해 암묵적으로 타입이 변환
암묵적 형 변환(implicit coercion) - 개발자가 의도적으로 타입을 변환
명시적 형변환(explicit coercion)
암묵적 형 변환
- '+' 연산 시 피연산자 중 하나가 문자열 타입이면 문자열 연결 연산자로 동작 (concat)
- 자바스크립트 엔진은 문자열이 아닌 정수를 문자열타입으로 암묵적으로 변환
*** 문자처럼 concat 연산
- 숫자 + 문자 = 문자
- 논리 + 문자 = 문자
*** 문자가 '숫자' 면 숫자 연산O (자바스크립트만의 특징)
- 숫자 - 문자 = 숫자
- 문자 - 숫자 = 숫자
- 숫자 * 문자 = 숫자
var n1 = 10;
var n2 = '20';
var n4 = n2 - n1 - '5';
console.log(n4); // 5
var n5 = n1 * n2;
console.log(n5); // 200
var n6 = 'hello' * 3;
console.log(n6); // NaN cf. Python은 문자 반복
- 논리 + 논리 = 숫자 (논리 간의 사칙연산 결과는 숫자)
- 논리 + 숫자 = 숫자
console.log(true + true); // 2
console.log(true + false); // 1
console.log(false + false); // 0
논리 타입으로 변환 - Truthy, Falsy
자바스크립트 엔진은 논리 타입이 아닌 값을
Truthy값(암묵적으로 참으로 평가) 또는
Falsy값(암묵적으로 거짓으로 평가)으로 구분
falsy : undefined, null, 0, NaN, ‘’(빈문자열)
// falsy : 0, '', null, undefined, NaN
if (0) console.log('hello-1');
if ('') console.log('hello-2');
if (null) console.log('hello-3');
if (undefined) console.log('hello-4');
if (NaN) console.log('hello-5');
truthy
if (99) console.log('hello-6'); // 출력ㅇ
if (-87.876) console.log('hello-7'); // 출력ㅇ
if (`ㅎㅇ`) console.log('hello-8'); // 출력ㅇ
if (' ') console.log('hello-9'); // 출력ㅇ
if ([10, 20, 30]) console.log('hello-10'); // 출력ㅇ
if ([]) console.log('hello-11'); // 출력ㅇ
if ({kind: '개'}) console.log('hello-12'); // 출력ㅇ
if (function() {}) console.log('hello-13'); // 출력ㅇ
*** truthy, falsy를 조건식으로도 사용 가능
for(var i = 1; i <= 10; i++) {
if(i % 2) { // 홀수는 나머지 1 if(1)
console.log(`${i}는 홀수입니다.`);
} else { // 짝수 if(0) falsy
console.log(`${i}는 짝수입니다.`);
}
}
명시적 형 변환
문자열 타입으로 변환
- 문자열이 아닌 값을 문자열 타입으로 변환하는 방법
- String 생성자 함수를 사용
- toString 메서드를 사용
- String 생성자 함수를 사용
var a = 10, b = 20;
// String 생성자 함수
var result = String(a) + String(b); // result: 1020
// toString 메서드
var result2 = a.toString() + b.toString(b); // result: 1020
숫자 타입으로 변환
- 숫자가 아닌 값을 숫자 타입으로 변환하는 방법
- Number 생성자 함수를 사용
- parseInt, parseFloat 함수를 사용
** parseInt 주의사항 : 소수라면 내림해서 정수로 반환
‘30.5’ → 30 - + / - 로 명시적 형 변환
var n7 = -'99';
var n8 = +'99';
console.log(typeof n7); // number
console.log(typeof n8); // number
** +’11’ ⇒ 11
** +’그만’ ⇒ NaN
var x1 = '30.5', y1 = '40.5';
// Number 생성자 함수
var result3 = Number(x1) + Number(y1); // 71
// parseInt 함수
var result4 = parseInt(x1) + parseInt(y1); // 70
// + / -
var result5 = +x1 + +y1; // 71
논리 타입으로 변환
- 논리 타입이 아닌 값을 논리 타입으로 변환하는 방법
- Boolean 생성자 함수를 사용
- ! 부정 논리 연산자를 두 번 사용
// 논리 타입으로 명시적 변환
console.log(Boolean('hello')); // true
console.log(Boolean(null)); // false
console.log(!!999); // true
console.log(!999); // false
console.log(!!undefined); // false
// 회원 로그인 여부 확인
function isLogin() {
// window.localStorage.getItem('LOGIN_ACCESS_TOKEN');
// return token !== null;
return !!window.localStorage.getItem('LOGIN_ACCESS_TOKEN');
}
const isLogin = () => !!window.localStorage.getItem('LOGIN_ACCESS_TOKEN');
단축 평가 (short circuit)
단축 평가 표현식 | 평가 결과 |
true || anything | true |
false || anything | anything |
true && anything | anything |
false && anything | false |
연산 시 조건이 결정되는 순간 다음 조건은 연산하지 않는 특성을 이용한 방법
- 첫번째 truthy를 찾는 OR연산자
한 번만 true이면 되기 때문에 true, truthy를 만날 때까지 연산
만약 모두 false라면 마지막 false, falsy 값을 반환
- 첫번째 falsy를 찾는 AND연산자
한 번이라도 false면 연산을 종료하기 때문에 false, falsy를 만날 때까지 연산
만약 모두 true라면 마지막 true, truthy 값을 반환
// 두 조건 같은 결과
if(조건이 참이면) {
console.log('blah blah~~~');
}
조건 && console.log('blah blah~~~');
** 리액트, 뷰
if문 쓰기 어려워서 단축평가 자주 사용
<h1>안녕하세요</h1>
login && <h2>ㅇㅇㅇ님 환영합니다</h2> <-- 조건부
쿠폰당첨여부 && sendCoupon();
!쿠폰당첨여부 && sendMessage(); 당첨이 안 됐을 때 메세지 보내기 (실무O)
쿠폰당첨여부 || sendMessage(); 당첨이 안 됐을 때 (실무X)
내게시물여부 && <button>삭제</button>
Javascript 배열
- 여러 자료를 하나의 변수에 넣어서 일목요연하게 순서를 만들어 정렬
- array 로 선언하면 물리적으로도 같은 위치에 메모리 저장 (속도에 도움)
var food1, … 각각 변수로 선언하면 메모리에 흩어져서 저장
배열 리터럴 (Array Literal)
- 배열 리터럴은 0개 이상의 요소를 쉼표로 구분하여 대괄호([])로 묶음
배열에 저장된 값 참조하기
- 배열에서 특정 데이터를 참조하려면 인덱스를 통해 참조
typeof 배열 object
var arr = [10, 20, 30, 40];
console.log(typeof arr); // object
console.log(arr[1]);
console.log(arr[2] ** 2);
console.log(arr[2]); // 계산결과를 저장 안했으니 여전히 30
arr[1] = 999;
arr[3]++;
console.log(arr); // [ 10, 999, 30, 41 ]
배열의 길이
- 배열의 길이란 배열에 저장할 수 있는 전체 항목 수
- 코드에서 배열의 길이를 얻으려면 배열 객체의 length 프로퍼티 사용
// 배열 데이터 수 확인
console.log(arr.length); // 4
console.log(`첫번째 데이터: ${arr[0]}`);
console.log(`마지막 데이터: ${arr[arr.length-1]}`);
배열 전체 순회 반복문 for ~ of
- for ~ of를 사용하면 현재요소의 인덱스 없이 빠르게 값을 얻어 낼 수 있음
- 배열의 항목 수 만큼 자동 반복하며 모든 항목을 사용한 후에 자동으로 종료
- for 안 배열에서 첫번째 값을 가져온 후 for에서 새로 선언한 변수에 저장한 후 for body 실행을 배열의 항목 개수만큼 반복
- 홀수 번째 데이터만 가져오는 것처럼 일부만 반복 불가(기존 for 문 사용)
for (let 변수 of 배열) { } : 처음부터 마지막 데이터까지 반복 (전체 순회)
// for ~ of 반복문 (배열 전용 반복문)
console.log('======================');
var weekDays = ['월', '화', '수', '목', '금', '토', '일'];
for (var day of weekDays) {
console.log(`${day}요일!!`);
}
배열 생성 관례
- 이름 복수형, -List 어미
- 마지막 요소에 콤마(,)
// 배열 생성 관례 : 이름 복수형, -List 어미
var fruits = ['grape', 'strawberry', 'orange'];
var fruitList = ['grape', 'strawberry', 'orange'];
var fruitArray = ['grape', 'strawberry', 'orange'];
fruits = ['grape', 'strawberry', 'orange', ];
console.log(fruits.length); // 3
var tags = [ // 세로로 작성하다보니 마지막 , 관례 지키면 좋음
'<li>오렌지</li>',
'<a href="#">링크</a>',
'<h1>로고</h1>',
'<h2>로고2</h2>',
];
배열 관련 메서드
push, pop
push: 배열의 끝에 요소를 추가
pop: 배열의 마지막 요소를 삭제
unshift, shift
unshift : 배열의 맨 처음에 요소를 추가 (배열 요소들의 index는 하나씩 밀린다 = +1)
shift : 배열의 첫번째 요소를 삭제
*** let deleted = Array.pop()
삭제되는 요소를 변수에 저장할 수 있음
메서드명 | 의미 |
indexOf(element) | 배열에서 요소를 검색하여 인덱스를 반환 |
includes(element) | 배열 내의 특정 요소가 포함되었는지 확인하여 논리값으로 반환 |
concat(array) | 주어진 배열의 요소들을 맨뒤에 추가한 후 복사한 배열을 반환 (원본 변화X) |
join(separator) | 배열의 모든 요소를 문자열로 변환 후 구분자로 연결(기본값 콤마) |
reverse() | 원본 배열의 순서를 반대로 뒤집음 (원본 변경됨, 복사본에 사용!!) |
slice(beginIndex, endIndex) |
배열의 인덱스 범위만큼 요소를 잘라서 복사한 배열을 반환 (원본 변화X) |
splice(beginIndex, [deleteCount], [newElement]) |
배열의 요소를 제거, 추가 (원본 변경됨) |
** slice()
- endIndex 는 포함하지 않음 (startIndex 이상 endIndex 미만)
- slice(3) : end 생략, 배열의 끝까지 복사
- slice(3, 999) : endIndex >= array.length 일 때 배열의 끝까지 복사
- slice() : 전체 복사
- slice(-3, -1) : 음수는 배열의 끝에서부터 카운트
(method) Array<string>.slice(start?: number | undefined, end?: number | undefined): string[]
Returns a copy of a section of an array. For both start and end, a negative index can be used to indicate an offset from the end of the array. For example, -2 refers to the second to last element of the array.
@param start
The beginning index of the specified portion of the array. If start is undefined, then the slice begins at index 0.
@param end
The end index of the specified portion of the array. This is exclusive of the element at the index 'end'. If end is undefined, then the slice extends to the end of the array.
** splice()
- deleteCount를 생략하거나 값이 array.length - start보다 크면 start부터의 모든 요소를 제거
- deleteCount가 0 이하라면 어떤 요소도 제거하지 않음. 이 때는 최소한 하나의 새로운 요소를 지정해야 함
- 배열에 추가할 요소는 세 번째 부터 작성, 아무 요소도 지정하지 않으면 splice()는 요소를 제거만 함
- splice(2, 1, '쿠키') : 하나의 요소를 수정할 수 있음
- splice(0, 1, '파스타', '보쌈') : 한 번에 여러 요소를 추가할 수 있음
- splice(3, 0, '햄버거') : 삭제 없이 요소를 추가할 수 있음
- var removed = myFish.splice(-2, 1); 끝에서 2번째 요소 하나를 삭제하고 변수 removed에 저장
- 삭제하지 않을 경우 removed 변수에는 [] 빈 배열 저장
var myFish = ["angel", "clown", "mandarin", "sturgeon"];
var removed = myFish.splice(-2, 1);
// myFish is ["angel", "clown", "sturgeon"]
// removed is ["mandarin"]
var myFish = ["angel", "clown", "mandarin", "sturgeon"];
var removed = myFish.splice(2, 0, "drum");
// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]
// removed is [], no elements removed
(method) Array<string>.splice(start: number, deleteCount?: number | undefined): string[] (+1 overload)
Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements.
@param start — The zero-based location in the array from which to start removing elements.
@param deleteCount — The number of elements to remove.
@returns — An array containing the elements that were deleted.
// deleteCount 1이면 수정
foodList.splice(0, 1, '파스타');
console.log(foodList); // [ '파스타', '볶음밥', '족발' ]
foodList.splice(0, 1, '파스타', '보쌈');
console.log(foodList); // [ '파스타', '보쌈', '볶음밥', '족발' ]
// deleteCount 0 + 새 요소 = 삽입
foodList.splice(2, 0, '마라탕');
console.log(foodList); // [ '파스타', '보쌈', '마라탕', '볶음밥', '족발' ]
foodList.splice(2); // 2번부터 끝까지 삭제
console.log(foodList); // [ '파스타', '보쌈' ]