일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
- nextInt
- Java script
- Java
- programmers
- BFS
- MySQL
- 오블완
- 프로그래머스
- Python
- 해시
- Computer Science
- Programming
- 반복문
- 백준
- Steve Jobs
- 자바의 정석(기초편)
- 영어원서
- java.lang 패키지
- JavaScript
- softeer
- 알고리즘
- 티스토리챌린지
- Spring Framework
- SQL
- 코딩테스트
- 관계형 데이터베이스
- Spring
- 소프티어
- StringTokenizer
- thinking differently
- Today
- Total
도라에몽 개발자
JS 데이터 본문
원시형
String, Number
- typeof 메소드: 결과값의 타입을 확인함.
const number = -123.1234
const pi = .14
console.log(number + undefined) // NaN -> Not a Number로, 숫자가 아닌 값을 의미함.
console.log(typeof(number + undefined)) // number
console.log(typeof(pi)) // number
- toFixed 메소드: 소수점 지정함.
- Number 함수: 결과값을 숫자 데이터로 변환함.
const a = 0.1 // 0은 생략하고 .1 으로 작성 가능함.
const b = 0.2 // 0은 생략하고 .2 으로 작성 가능함.
console.log((a + b).toFixed(1)) // 0.3
console.log(typeof (a + b).toFixed(1)) // string
console.log(typeof Number((a + b).toFixed(1))) // number
Boolean, Null, Undefined
- Boolean
- 논리 데이터 타입
- true / false
- true인 경우에는 결과값이 출력되나, false인 경우에는 결과값이 출력되지 않음.
const a = true
const b = false
if (a) { console.log("Hello ") } // Hello 이라고 정상적으로 출력됨.
if (b) { console.log("World!") } // 출력되지 않음.
- Null
- 값이 없는 상태임을 명시적으로 나타냄.
cf. undefined: 값이 없는 상태임을 암시적으로 나타냄.
let age = null
// let age // console.log(age) 출력값: undefined
console.log(age) // null
setTimeout(function () {
age = 25
console.log(age) // 25
}, 1000) // 1000 -> 1초 뒤에 결과값 출력
// 객체데이터 user 생성
const user = {
name: 'JJACK',
age: 25,
email: null
}
console.log(user.name) // JJACK
console.log(user.age) // 25
console.log(user.email) // null
console.log(user.none) // undefined
- 이메일 값은 아직 비어 있음을 null을 통해 명시적으로 나타내었음.
- none 값은 아직 비어 있음을 undefined를 출력함으로써 암시적으로 나타냄.
참조형
Array (배열 데이터)
▼ 배열 리터럴: const 변수명 = [ '요소1', '요소2', ... ]
- 대괄호 안에 요소(=아이템)를 넣어줌.
// const fruits = new Array('Apple', 'Banana', 'Cherry')
// fruits 배열을 문자 리터럴을 활용하여 아래와 같이 나타낼 수 있음.
const fruits = ['Apple', 'Banana', 'Cherry']
console.log(fruits) // 0: "Apple", 1: "Banana", 2: "Cherry"
console.log(fruits[0]) // Apple
console.log(fruits[1]) // Banana
console.log(fruits[2]) // Cherry
console.log(fruits.length) // 3
console.log([fruits.length - 1]) // Cherry
Object (객체 데이터)
key: value 형태로 만들어짐.
- key: 속성(property)
- value: 값
▼ 생성자 사용하여 새로운 객체 생성
// 생성자 사용하여 새로운 객체 생성
const user = new Object() // user 객체 생성
user.name = "JJACK" // key: value 형태로 출력됨.
user.age = 25 // key: value 형태로 출력됨.
console.log(user) // {name: 'JJACK', age: 25} <- 객체 리터럴 방식으로 데이터 생성함.
▼ 함수 활용 및 새로운 객체 생성
// 함수 활용
function User() {
this.name = "JJACK"
this.age = 25
}
const user = new User // 새로운 User 객체를 생성하여 user 변수에 할당
console.log(user)
▼ 중괄호({...})를 사용한 리터럴 방식으로 새로운 객체 데이터 생성
// 리터럴 방식(중괄호{} 안에 요소 나열)으로 객체 데이터 생성
const user = {
name: "JJACK",
age: 25
}
// 점 표기법
console.log(user.name) // JJACK
console.log(user.age) // 25
// 대괄호 표기법
console.log(user['name']) // JJACK
console.log(user['age']) // 25
▼ 객체 안의 객체 값
const userA = {
name: 'JJACK',
age: 25
}
const userB = {
name: 'MARK',
age: 24,
parent: userA
}
console.log(userB.parent.name) // JJACK
console.log(userB['parent']['name']) // JJACK
const users = [userA, userB] // users 배열의 요소: userA, userB
console.log(users[0]['name']) // JJACK (userA의 name 값)
Function (함수)
function hello() {
console.log('Hello?')
}
hello() // Hello? (함수 호출하여 결과 출력)
hello // 함수값이 그대로 출력됨 -> { console.log("Hello?"); }
function getNumber() {
return 123
}
console.log(getNumber) // getNumber() { return 123; }
console.log(typeof getNumber) // function
console.log(getNumber()) // 123
console.log(typeof getNumber()) // number
const getNumber = function () {
return 123
}
console.log(getNumber)
console.log(typeof getNumber)
console.log(getNumber())
console.log(typeof getNumber())
const a = function () {
console.log('A')
}
const b = function(c) {
console.log(c)
c()
}
b(a)
// 결과
// f() { console.log("A"); }
// A
형 변환(Type Conversion)
숫자 데이터, 문자 데이터, 함수, 객체, 배열 등은 모두 형(Type)에 해당되는 개념임.
- 일치 연산자: === (equal 기호 3개)
- 동등 연산자: == (equal 기호 2개) ← *형 변환(type conversion) 후 비교한 결과가 나오게 되므로 주의해야 함.
Ex. boolean 데이터와 숫자 또는 문자 데이터를 동등 연산자(==)를 통해 비교하면, 결과가 true로 나오게 됨. (*잘못된 결과 출력)
참과 거짓(Truthy & Falsy)
거짓(Falsy)에 해당하는 항목
- false
- 숫자 0
- null
- undefined
- NaN
- '' (빈 문자)
- 0n (BigInt; 숫자 0 뒤에 알파벳 n이 붙은 형태)
cf. 문자 0 === true → 문자 0은 참(Truthy)에 해당함.
cf. 0 이외의 대부분의 숫자는 true에 해당함.
// 숫자 0 === false
if (0) {
console.log('참(Truthy)') // 아무것도 출력되지 않음.
}
// 문자 0 === true
if ('0') {
console.log('참(Truthy)') // 참(Truthy) 이라고 정상 출력됨.
}
// 0을 제외한 숫자 === true
if (25) {
console.log('참(Truthy)') // 참(Truthy) 이라고 정상 출력됨.
}
속성을 사용하여 참과 거짓(Truthy & Falsy) 구분
length 속성을 사용하여 배열의 길이를 확인하여 배열 내 아이템(요소)이 들어있는지, 없는지 확인하여 true / false 결과 확인함.
// Truthy
const fruits = ['Melon', 'Cherry']
if (fruits.length) {
console.log('아이템이 들어있음.') // fruits.length가 2임에 따라 아이템이 들어있음. 출력됨.
}
// Falsy
const beverage = []
if (beverage.length) {
console.log('아이템이 들어있음.') // fruits.length가 0임에 따라 아이템이 들어있음. 출력되지 않음.
}
데이터 타입 확인
typeof 활용
▼ typeof ___ === ___ ← 두 가지의 데이터 타입 비교한 결과 출력
// typeof 활용
console.log(typeof 'Hello' === 'string') // true
console.log(typeof 123 === 'number') // true
console.log(typeof false === 'boolean') // true
console.log(typeof undefined === 'undefined') // true
// null, 배열, 객체 데이터의 경우, typeof로 type 확인 불가함.
console.log(typeof null === 'object') // null === 객체 데이터 -> true
console.log(typeof [] === 'object') // 배열 데이터 === 객체 데이터 -> true
console.log(typeof {} === 'object') // 객체 데이터 === 객체 데이터 -> true
console.log(typeof function () {} === 'function') // 익명 함수 === 함수 -> true
- 문자, 숫자, boolean, undefined 데이터 및 함수의 경우 typeof 활용 시 올바른 결과를 확인할 수 있음.
- null, 배열, 객체 데이터의 경우에는 객체데이터와 비교 시 모두 참으로 출력되기 때문에 잘못된 결과가 출력될 위험이 있음.
constructor 활용
▼ ___.constructor === ___ ← 두 가지의 데이터 타입 비교한 결과 출력
- typeof로 비교할 수 없는 배열, 객체 데이터의 경우, 이와 같은 constructor를 활용하여 데이터 타입을 비교할 수 있음.
- 다만, null은 constructor 활용할 수 없음. 다른 방법으로, Object.prototype.toString.call(null).slice(8, -1) === 'Null' 과 같이 작성하여 비교해야 함.
→ Object.prototype: 새로운 객체를 생성함.
→ toString 메소드 및 call 메소드를 통해 null이라는 데이터를 새로운 객체로 호출하여 불러옴.
→ slice 메소드: 위와 같은 절차로 나온 결과인 문자열의 8번째에서 바로 앞까지만 출력하라는 의미임.
// constructor 활용
console.log([].constructor == Array) // true
console.log({}.constructor == Object) // true
console.log(null.constructor) // Error -> null 데이터는 constructor로 구분 불가
console.log(Object.prototype.toString.call(null)) // [object Null]
console.log(Object.prototype.toString.call(null).slice(8,-1)==='Null') // true
function (함수) 활용
▼ function (...) {...} : 재사용 가능한 함수를 선언하여, 해당 함수를 활용하여 데이터 타입 비교한 결과 출력해냄.
함수 선언 후 해당 함수를 통해 아래와 같은 기능을 사용할 수 있음.
- 데이터 타입 확인 가능
- 데이터 타입 비교 가능
function checkType(data) { // checkType 이라는 함수 생성
return Object.prototype.toString.call(data).slice(8, -1)
}
// checkType 함수를 통해 데이터 타입 확인
console.log(checkType('Hello')) // String
console.log(checkType(123)) // Number
console.log(checkType(false)) // Boolean
console.log(checkType(undefined)) // Undefined
console.log(checkType(null)) // Null
console.log(checkType([])) // Array
console.log(checkType({})) // Object
// 데이터 타입 비교
console.log(checkType('Hello') === 'String')
console.log(checkType(123) === 'Number')
console.log(checkType(false) === 'Boolean')
console.log(checkType(undefined) === 'Undefined')
console.log(checkType(null) === 'Null')
console.log(checkType([]) === 'Array')
console.log(checkType({}) === 'Object')
'LANGUAGE > JavaScript' 카테고리의 다른 글
연산자와 구문 (1) | 2023.12.22 |
---|---|
Node.js 설치 시 참고사항 (0) | 2023.12.21 |
DOM API (Document Object Model, Application Programming Interface) (1) | 2023.12.16 |
변수, 함수(function), 조건문(if, else) (0) | 2023.12.16 |
표기법, 주석, 데이터 종류(자료형) (0) | 2023.12.16 |