-
Section 6. 자바스크립트 빌트인 전역 프로퍼티와 함수자바스크립트 2023. 3. 30. 15:05
I. 빌트인 전역 프로퍼티
스스로 다른 프로퍼티나 메서드를 갖지 않고 값만 반환하는 특징이 있다.
console.log(globalThis.Infinity); //Infinity console.log(globalThis.NaN); //NaN console.log(globalThis.undefined); //undefined console.log(globalThis.globalThis); //Window {window: Window, self: Window, document: document, name: '강남', location: Location, …} console.log( globalThis == globalThis.globalThis, globalThis == globalThis.globalThis.globalThis, globalThis == globalThis.globalThis.globalThis.globalThis ); //true true true
Infinity, NaN, undefined등의 원시값들은 이 프로퍼티들을 가리킨다는 것을 알 수 있다.
그리고 globalThis안에는 globalThis가 또 있는데 이유는 globalThis는 스스로에 대한 참조를 프로퍼티로 포함하기 때문이다.
II. 빌트인 전역 함수
1. eval - 문자열로 된 코드를 받아 실행
값을 반환하는 코드(표현식)이라면 해당 값을 반환한다.
const x = eval('1 + 2 + 3'); // 객체나 함수의 리터럴은 괄호로 감싸야 함 const obj = eval('({a: 1, b: 2})'); console.log(x, obj); //6 {a: 1, b: 2}
값을 반환하는 것을 알 수 있다.
표현식이 아닐 경우에는 해당 코드를 실행한다.
const code = ` let x = 1; console.log(x++, x); `; eval(code); //1 2
그냥 이런게 있다는 것만 알고 넘어가자. 왜냐하면 eval은...
- 보안에 매우 취약하다
- 엔진이 코드를 최적화하지 못하므로 처리 속도가 느리다
2. isFinite- 유한수 여부 반환
console.log( isFinite(1), isFinite(0), isFinite('1'), isFinite(null) ); //true true true true
유한수이거나 유한수로 평가될 수 있는 (null은 0)값은 true로 반환된다.
console.log( isFinite(1/0), isFinite(Infinity), isFinite(-Infinity), isFinite(NaN), isFinite('abc') ); //false false false false false
반대로 무한수이거나 수로 평가될 수 없는 값은 false로 반환된다.
3. isNaN - NaN 여부 반환
console.log( isNaN(NaN), isNaN('abcde'), isNaN({}), isNaN(undefined) ); //true true true true
숫자로 인식될 수 없는 값은 true로 반환된다.
Number 타입이 아닌 경우 Number로 변환하여 평가한다. NaN도 타입은 Number다
4. parseFloat - 인자로 받은 값을 실수로 변환
console.log( parseFloat(123.4567), parseFloat('123.4567'), parseFloat(' 123.4567 ') ); //123.4567 123.4567 123.4567
문자열의 경우 앞뒤공백은 무시한다.
console.log( parseFloat('123.0'), parseFloat('123'), parseFloat(' 123ABC '), parseFloat([123, 456, 789]) ); //123 123 123 123
숫자로 시작할 경우 읽을 수 있는 부분까지 숫자로 변환한다.
배열의 경우 첫 요소가 숫자면 해당 숫자를 반환한다.
console.log( parseFloat('ABC123'), parseFloat({x: 1}), parseFloat([]), parseFloat(['a', 1, true]) ); //NaN NaN NaN NaN
기타 숫자로 변환이 안 되는 경우 NaN을 반환한다.
5. parseInt - 인자로 받은 값을 정수 (타입은 실수)로 변환
console.log( parseInt(123), parseInt('123'), parseInt(' 123.4567 '), parseInt('345.6789') ); //123 123 123 345
소수점 뒤로 오는 숫자는 버린다. 반올림하지 않는다
console.log( parseInt('abc'), parseInt('{}'), parseInt('[]') ); //NaN NaN NaN
역시 숫자로 변환이 안 되는 경우 NaN을 반환한다.
두 번째 인자로 숫자(2~36)을 넣으면
console.log( parseInt('11'), parseInt('11', 2), parseInt('11', 8), parseInt('11', 16), parseInt('11', 32), parseInt('11', 37), parseInt('11', 'A'), ); //11 3 9 17 33 NaN 11
주어진 값을 해당 진법의 숫자로 해석해서 10진법 숫자로 반환한다.
무효한 숫자는 NaN으로 반환되는 것을 볼 수 있다.
6. encodeURI, encodeURIComponent
const searchURI = 'https://www.google.com/search?q=얄코'; const encodedURI = encodeURI(searchURI); console.log(encodedURI); //https://www.google.com/search?q=%EC%96%84%EC%BD%94
searchURI를 주소창에 쳐보면 그대로 나오지만 그 주소를 메모장에 복사해보면 알수 없는 문자로 바뀌어서 출력되는 것을 볼 수 있다. 이렇게 되는 이유는 다음과 같다.
- URI(인터넷 자원의 주소)는 아스키 문자 셋(알파벳이나 우리가 쓰는 특수 문자들)으로만 구성되어야 하기 때문이다
- 아스키가 아닌 문자(한글 등)와 일부 특수문자를 포함한 URI를 유효하게 인코딩 한다.
즉, 얄코 이부분은 아스키 문자 셋이 아니기 때문에 아스키 문자 셋을 이용해서 변환되는(인코딩) 것이다.
const keyword = '얄코'; const encodedKeyword = encodeURIComponent(keyword); console.log(encodedKeyword); //%EC%96%84%EC%BD%94
keyword가 변환된 것을 볼 수 있다. 그런데 얼핏보면 encodeURI와 encodeURIComponent가 하는 일이 같은 것 같다.
둘의 차이는 다음과 같다.
const raw = '?q=얄코'; console.log(encodeURI(raw)); //?q=%EC%96%84%EC%BD%94 console.log(encodeURIComponent(raw)); //%3Fq%3D%EC%96%84%EC%BD%94
?q= 이 부분을 encodeURI에서는 그대로 놔뒀고 encodeURIComponent는 그 부분까지 바꿔버린 것을 볼 수 있다.
이유는 다음과 같다.
- URI에서 특정 기능을 갖는 =, ?, & 등을 인코딩하는가의 여부
- encodeURI는 인자를 완성된 URI로, encodeURIComponent는 요소로 인식하기 때문이다.
7. decodeURI, decodeURIComponent
encode가 있으면 decode도 있다. decode는 encode와 반대로 동작한다.
const encodedURI = 'https://www.google.com/search?q=%EC%96%84%EC%BD%94'; const decodedURI = decodeURI(encodedURI); console.log(decodedURI); //https://www.google.com/search?q=얄코 const encodedComp = '%EC%96%84%EC%BD%94'; const decodedComp = decodeURI(encodedComp); console.log(decodedComp); //얄코
'자바스크립트' 카테고리의 다른 글
Section 6. 자바스크립트 Number 객체 (0) 2023.03.31 Section 6. 자바스크립트 String 객체 (0) 2023.03.30 Section 6. 자바스크립트 전역 객체와 표준 빌트인 객체 (0) 2023.03.30 Section 5. 자바스크립트 객체의 스프레드와 디스트럭쳐링 (0) 2023.03.30 Section 5. 자바스크립트 상속 (0) 2023.03.30