데이터 타입 ( 숫자, 문자 ) 정리

배병일 ㅣ 2023. 6. 9. 19:20

JS 에서 코드를 작성할 때 데이터 타입이 어떻게 되는지 이해하기 위해 작성하는 글

 

JS에서 data type은 runtime 때 정해진다.
// 데이터 타입
// runtime : run하는 time
// 코드를 작성할 때가 아니라, 실제 코드가 실행될 때
// -> 옆에 터미널에 코드가 실행될 때
// 그 때, 데이터 타입이 결정된다.
// java : string a = "abc"
// const a = "abc"
숫자
  • 정수
let num1 = 10
// let num1 = "10"
// "" 넣지 않을 경우 number 타입 "" 넣을 경우 string 타입
console.log(num1) // 10
console.log(typeof num1) // number
console.log(typeof(num1)) // number
// typeof : 타입 확인


let num1 = "10"
console.log(num1) // 10
console.log(typeof num1) // string

// 실제 num1의 값은 같아 보이지만 타입이 다른 걸 확인 할 수 있다.
  • 실수 ( float )
let num2 = 3.14
console.log(num2) // 3.14
console.log(typeof num2) // number
  • 지수 ( Exp )
let num3 = 2.5e5 // 2.5 x 10^5
console.log(num3) // 250000
console.log(typeof num3) // number
  • NaN : Not a Number
let num4 = "hello" / 2
console.log(num4) // NaN
  • Infinity ( 무한대 )
let num5 = 1 / 0
console.log(num5) // Infinity
console.log(typeof num5) // number
  • -Infinity ( 무한대 )
let num6 = -1 / 0
console.log(num6) // -Infinity
console.log(typeof num6) // number

 

문자
문자 : string ( 문자열 = 문자의 나열 )  ' ' = " "
  • 문자열 확인
let str = "hello"
console.log(str) // hello
console.log(typeof str) // string
  • 문자열 길이 확인 ( length )
let str = "hello"
console.log(str.length) // 5
  • 문자열 결합
let str1 = "hello"
let str2 = "world"

console.log( str1 + str2 ) // helloworld

let result = str1.concat(str2)  

console.log(result) // helloworld
  • 문자열 자르기 ( substr / slice )
let str3 = "hello, world"

console.log(str3.substr(7, 5)) // oworld
// substr(시작열, 시작열부터 몇번째까지)

console.log(str3.slice(7, 12)) // world
// slice(시작열, 몇번째열까지)
  • 문자열 검색 ( search )
let str4 = "hello, world"

console.log(str4.search("world")) // 7
// serch("해당문자열이 몇번째부터 시작되는지")
  • 문자열 대체 ( replace )
let str5 = "hello, world"

let result1 = str5.replace("world", "JS")

console.log(result1) // hello, JS
  • 문자열 분할 ( split )
let str6 = "a, b, c"

let result2 = str6.split(",")

console.log(result2) // [ 'a', ' b', ' c' ]
// split("해당 문자를 기준으로 잘라 배열의 형태로 담는다.")