JavaScript

SongE·2022년 4월 20일
1

(KDT FE2) Study Note 🧾

목록 보기
4/10
post-thumbnail

Essentials

1. JS 시작하기

1.1 데이터 타입 확인

console.log('Hello world!') // ; 안붙여도 실행된다. 단, 특수한 경우에는 필요

console.log(typeof 'Hello world!') //string
console.log(typeof 123) // number
console.log(typeof true) // boolean
console.log(typeof undefined) // undefined
console.log(typeof null) // object
console.log(typeof {}) // object
console.log(typeof []) // object

function getType(data) {
  return Object.prototype.toString.call(data)
}

console.log(getType(123)) // [object Number]
console.log(getType(false)) // [object Boolean]

function getType(data) {
  return Object.prototype.toString.call(data).slice(8, -1)
}

import getType from './getType';

console.log(getType(123)) // Number
console.log(getType(false)) // Boolean
console.log(getType(null)) //Null
console.log(getType({})) // Object
console.log(getType([])) // Array

1.2 산술, 할당 연산자

1.2.1 산술 연산자(arithmetic operator)

console.log(1+2) //3
console.log(5-7) //-2
console.log(3*4) // 12
console.log(10/2) //5
console.log(7%5) //2 : 7을 5로 나눈 나머지 연산자

1.2.2 할당 연산자(assignment operator)

let a = 2
console.log(a) // 2
a +=1 // a = a + 1 : 모든 산술 연산자 적용 가능
console.log(a) // 3

1.3 비교, 논리 연산자

1.3.1 비교 연산자(comparison operator)

const a = 1
const b = 1
console.log(a===b) // true : 일치 연산자, a와 b가 일치하는지
function isEqual(x, y) {
  return x === y
}
console.log(isEqual(1, 1)) // true
console.log(isEqual(2,'2')) // false : 숫자데이터와 문자데이터 이기 때문
const a = 1
const b = 1
console.log(a!==b) // false : 불일치 연잔자, a와 b가 서로 다른지
console.log(a < b) // false : a가 b보다 작은지
console.log(a > b) // false : a가 b보다 큰지
console.log(a >= b) // true : a가 b보다 크거나 같은지
console.log(a <= b) // true : a가 b보다 작거나 같은지

1.3.2 논리 연산자(logical operator)

const a = 1 === 1
const b = 'AB' === 'AB'
const c = false
console.log(a) // true
console.log(b) // true
console.log(c) // false
console.log('&&:', a && b && c) // false : 모두 true여야 true가 되는 AND 연산자
console.log('||:', a || b || c) // true : true가 하나 이상이면 true가 되는 OR 연산자
console.log('!: ', !a) // false : true면 false를 나타내는 부정 연산자

1.4 삼항 연산자

const a = 1 < 2 
if (a) {
  console.log('참') // 참
} else {
  console.log('거짓')
} 
console.log(a ? '참' : '거짓') // 조건 ? 참값 : 거짓값

1.5 조건문 If Else

--JS getRandom.js--
export default function random() {
  return Math.floor(Math.random() * 10)
}

--main.js--
import random from './getRandom'

const a = random()

if (a === 0) {
  console.log('a is 0')
} else if (a === 2) {
  console.log('a is 2')
} else if (a === 4) {
  console.log('a is 4')
} else {
  console.log('rest...')
}

1.6 조건문 Switch

import random from './getRandom'

const a = random()

switch (a) {
  case 0:
    console.log('a is 0')
    break
  case 2:
    console.log('a is 2')
    break  
  case 4:
    console.log('a is 4')
   break  
  default:
    console.log('rest...') 
}

1.7 반복문 For

for (시작조건; 종료조건; 변화조건) { }

const ulEl = document.querySelector('ul')

for (let i = 0; i < 10; i +=1) {
  const li = document.createElement('li')
  li.textContent = `list-${i + 1}`
  if ((i + 1) % 2 === 0) {
    li.addEventListener('click', function () {
      console.log(li.textContent)
    })
  }
  ulEl.appendChild(li)
}

1.8 변수 유효범위

변수유효범위재할당중복선언호이스팅전역등록
const블록 레벨XXXX
let블록 레벨OXXX
var함수 레벨OOOO

1.9 형 변환

1.9.1 Truthy(참 같은 값)

true, {}, [], 1, 2, 'false', -12, '3.14' ...

1.9.2 Falsy(거짓 같은 값)

false, ' ', null, undefined, 0 -0, NaN(Not a Number)

2. JS 함수

2.1 함수 복습

const sum = function (x, y) { // 매개변수
  if (x < 2) {
    return 123 // 반환과 종료를 의미함
  }
  return x + y 
}

console.log(sum(1,3)) // 123

const sum = function (x, y) { 
  console.log(arguments)
  return arguments[0] + arguments[1]
}

console.log(sum(1,3)) // 4

2.2 화살표 함수

( ) => { } vs function ( ) { }

const double = function (x) {
  return x * 2
}
console.log('double: ', double(7))

const doubleArrow1 = x => x * 2
console.log('doubleArrow1: ', doubleArrow1(7))

const doubleArrow2 = x => ({ name: 'Heroppy' }) // 객체데이터 반환 시
console.log('doubleArrow2: ', doubleArrow2(7))

2.3 즉시실행함수

IIFE, Immediately-Invoked Function Expression

const a = 7
function double() {
  console.log(a * 2) // 14
}
double(); // 함수를 실행해야지 값을 출력

(function double() {
  console.log(a * 2) // 14
})() // 즉시실행함수로 바로 출력

2.4 호이스팅(Hoisting)

함수 선언부가 유효범위 최상단으로 끌어올려지는 현상

const a =7

double()

function double () {
  console.log(a * 2) // 14
}

2.5 타이머 함수

  • setTimeout(함수, 시간): 일정 시간 후 함수 실행
  • setInterval(함수, 시간): 시간 간격마다 함수 실행
  • clearTimeout(): 설정된 Timeout 함수를 종료
  • clearInterval(): 설정된 Interval 함수를 종료
const timer = setTimeout( () => {
  console.log('Heropy!')
}, 3000)

const h1El = document.querySelector('h1')
h1El.addEventListener('click', () => {
  clearTimeout(timer)
})

const timer = setInterval( () => {
  console.log('Heropy!')
}, 3000)

const h1El = document.querySelector('h1')
h1El.addEventListener('click', () => {
  clearInterval(timer)
})

2.6 콜백(Callback)

함수의 인수로 사용되는 함수

function timeout(cb) {
  setTimeout(() => {
    console.log('Heropy!')
    cb()
  }, 3000)
}
timeout(() => {
  console.log('Done!')
})

3. JS 클래스

3.1 생성자 함수(prototype)

function User(first, last) {
  this.firstName = first
  this.lastName = last
}
User.prototype.getFullName = function () {
  return `${this.firstName} ${this.lastName}`
}

const heropy = new User('Heropy', 'Park')
const amy = new User('Amy', 'Clarke')
const neo = new User('Neo', 'Smith')

console.log(heropy.getFullName())
console.log(amy.getFullName())
console.log(neo.getFullName())

3.2 this

  • 일반(Normal) 함수는 호출 위치에서 따라 this 정의!
  • 화살표(Arrow) 함수는 자신이 선언된 함수 범위에서 this 정의!
const heropy = {
  name: 'Heropy',
  normal: function () {
    console.log(this.name)
  },
  arrow: () => {
    console.log(this.name)
  }
}
heropy.normal() // Heropy
heropy.arrow() // Undefined

const amy = {
  name: 'Amy',
  normal: heropy.normal,
  arrow: heropy.arrow
}
amy.normal()
amy.arrow()

function User(name) {
  this.name = name
}
User.prototype.normal = function () {
  console.log(this.name)
}
User.prototype.arrow = () => {
  console.log(this.name)
}

const heropy = new User('Heropy')

heropy.normal() // Heropy
heropy.arrow() // Undefined


const timer = {
  name: 'Heropy!!',
  timeout: function () {
    setTimeout(function () {
      console.log(this.name)
    }, 2000)
  }
}
timer.timeout() // Undefined

const timer = {
  name: 'Heropy!!',
  timeout: function () {
    setTimeout(() => {
      console.log(this.name)
    }, 2000)
  }
}
timer.timeout() // Heropy!!

3.3 ES6 Classes

normal: function ( ) { } = normal( ) { } 생략 가능!

function User(first, last) {
  this.firstName = first
  this.lastName = last
}
User.prototype.getFullName = function () {
  return `${this.firstName} ${this.lastName}`
}

class User {
  constructor(first, last) {
    this.firstName = first
    this.lastName = last
  }
  getFullName() {
    return `${this.firstName} ${this.lastName}`
  }
}

const heropy = new User('Heropy', 'Park')
const amy = new User('Amy', 'Clarke')
const neo = new User('Neo', 'Smith')

console.log(heropy.getFullName()) // Heropy Park
console.log(amy.getFullName()) // Amy Clarke
console.log(neo.getFullName()) // Neo Smith

3.4 상속(확장)

class Vehicle {
  constructor(name, wheel) {
    this.name = name
    this.wheel = wheel
  }
}
const myVehicle = new Vehicle('운송수단', 2)
console.log(myVehicle)

class Bicycle extends Vehicle {
  constructor(name, wheel) {
    super(name, wheel)
  }
}
const myBicycle = new Bicycle('삼천리', 2)
const daughtersBicycle = new Bicycle('세발', 3)
console.log(myBicycle)
console.log(daughtersBicycle)

class Car extends Vehicle {
  constructor(name, wheel, license) {
    super(name, wheel)
    this.license = license
  }
}
const myCar = new Car('벤츠', 4, true)
const daughtersCar = new Car('포르쉐', 4, false)
console.log(myCar)
console.log(daughtersCar)

JavaScript Level up

1. JS 데이터

1.1 문자

const str = '    Hello world   '
console.log(str.trim()) // Hello world

const str = 'thesecon@gmail.com'
console.log(str.match(/.+(?=@)/)[0]) // thesecon

const str = 'Hello world!'
console.log(str.indexOf('world')) // 6
console.log(str.indexOf('Heropy') !== -1) // false
console.log(str.slice(0, 3)) // Hel
console.log(str.replace(' world!', '')) // Hello

const str = '0123'
console.log(str.length) // 4

1.2 숫자와 수학

const pi = 3.14159265358973
console.log(pi) // 3.14159265358973

const str = pi.toFixed(2)
console.log(str) // 3.14
console.log(typeof str) // string

const integer = parseInt(str)
const float = parseFloat(str)
console.log(integer) // 3 (정수 출력하면서 숫자데이터로 변환)
console.log(float) // 3.14 (소숫점 까지 출력하면서 숫자데이터로 변환)
console.log(typeof integer, typeof float) // number number

console.log('abc: ', Math.abs(-12)) // abs: 12 (절댓값)
console.log('min: ', Math.min(2, 8)) // min: 2 (최솟값)
console.log('max: ', Math.max(2, 8)) // max: 8 (최댓값)
console.log('ceil: ', Math.ceil(3.14)) // ceil: 4 (올림)
console.log('floor: ', Math.floor(3.14)) // floor: 3 (내림)
console.log('round: ', Math.round(3.14)) // round: 3 (반올림)
console.log('random: ', Math.random()) // random: 0.812349882123 (랜덤한 숫자)

1.3 배열

1.3.1 .length

  • 배열데이터 안의 아이템의 갯수를 반환해주는 메소드
const numbers = [1, 2, 3, 4]
const fruits = ['Apple', 'Banana', 'Cherry'] 

console.log(numbers.length) // 4
console.log(fruits.length) // 3
console.log([1, 2].length) // 2
console.log([].length) // 0

1.3.2 .concat()

  • 두 개의 배열 데이터를 병합해서 새로운 배열 데이터를 반환해주는 메소드
  • 원본의 배열데이터가 수정되지 않는다.
const numbers = [1, 2, 3, 4]
const fruits = ['Apple', 'Banana', 'Cherry'] 

console.log(numbers.concat(fruits)) // [1, 2, 3, 4, 'Apple', 'Banana', 'Cherry]
console.log(numbers) // [1, 2, 3, 4]
console.log(fruits) // ['Apple', 'Banana', 'Cherry'] 

1.3.3 .forEach()

  • 배열데이터의 아이템의 갯수만큼 특정한 콜백 함수를 반복적으로 실행하는 용도로 사용되는 메소드
const numbers = [1, 2, 3, 4]
const fruits = ['Apple', 'Banana', 'Cherry'] 

fruits.forEach(function (element, index, array) {
  console.log(element, index, array)
})  //Apple 0 (3) ['Apple', 'Banana', 'Cherry']
   // Banana 1 (3) ['Apple', 'Banana', 'Cherry']
  // Cherry 2 (3) ['Apple', 'Banana', 'Cherry']

1.3.4 .map()

  • 배열데이터의 아이템의 갯수만큼 특정한 콜백 함수를 반복적으로 실행하는 용도로 사용되는 메소드
  • return 키워드를 통해 반환한 데이터를 새로운 배열로 만들어서 사용할 수 있다.
const numbers = [1, 2, 3, 4]
const fruits = ['Apple', 'Banana', 'Cherry'] 

const a = fruits.forEach((fruit, index) => {
  console.log(`${fruit}-${index}`)
})
console.log(a) // undefined

const b = fruits.map(function (fruit, index) {
   return `${fruit}-${index}`
})
console.log(b) // ['Apple-0', 'Banana-1', 'Cherry-2']

const c = fruits.map((fruit, index) => ({
  id: index, 
  name: fruit // return 생략
}))
console.log(c) 
// 0: {id: 0, name: 'Apple'}
// 1: {id: 1, name: 'Banana'}
// 2: {id: 2, name: 'Cherry'}

1.3.5 .filter()

  • 배열 데이터안의 각각의 아이템들을 특정한 기준으로 필터링하여 새로운 배열을 반환시키는 메소드
  • map과 다르게 원본의 아이템 갯수와 다를 수 있음
const numbers = [1, 2, 3, 4]
const fruits = ['Apple', 'Banana', 'Cherry'] 

const a = numbers.map(number => number < 3 )
console.log(a) // [true, true, false, false]


const b = numbers.filter(number => number < 3 )
console.log(b) // [1, 2]

console.log(numbers) // [1, 2, 3, 4] !! 원본 배열은 수정되지 않음!

1.3.6 .find()

  • 특정 조건에 맞는 아이템을 찾아주는 메소드

1.3.7 .findIndex()

  • 특정 조건에 맞는 아이템의 인덱스 번호를 찾아주는 메소드
const numbers = [1, 2, 3, 4]
const fruits = ['Apple', 'Banana', 'Cherry'] 

const a = fruits.find(fruit => /^B/.test(fruit))
console.log(a) // Banana

const b = fruits.findIndex(fruit => /^C/.test(fruit))
console.log(b) // 2

1.3.8 .includes()

  • 특정 인수가 배열에 포함되어 있는지 확인하는 메소드
const numbers = [1, 2, 3, 4]
const fruits = ['Apple', 'Banana', 'Cherry'] 

const a = numbers.includes(3)
console.log(a) // true

const b = fruits.includes('HEROPY')
console.log(b) // false

1.3.9 .push()

  • 배열의 가장 뒷 쪽에 인수를 삽입하는 메소드
  • 원본 수정됨 주의!

1.3.10 unshift()

  • 배열의 가장 앞 쪽에 인수를 삽입하는 메소드
  • 원본 수정됨 주의!
const numbers = [1, 2, 3, 4]
const fruits = ['Apple', 'Banana', 'Cherry'] 

numbers.push(5)
console.log(numbers) // [1, 2, 3, 4, 5]

numbers.unshift(0)
console.log(numbers) // [0, 1, 2, 3, 4, 5]

1.3.11 .reverse()

  • 배열의 아이템의 순서를 뒤집어내는 메소드
  • 원본 수정됨 주의!
const numbers = [1, 2, 3, 4]
const fruits = ['Apple', 'Banana', 'Cherry'] 

numbers.reverse()
fruits.reverse()

console.log(numbers) // [4, 3, 2, 1]
console.log(fruits) // ['Cherry', 'Banana', 'Apple']

1.3.12 .splice()

  • 배열데이터에서 특정한 아이템을 삭제하거나 삽입할때 사용하는 메소드
  • 원본 수정됨 주의!
const numbers = [1, 2, 3, 4]
const fruits = ['Apple', 'Banana', 'Cherry'] 

numbers.splice(2, 1, 99) 
console.log(numbers) // [1, 2, 99, 4]

fruits.splice(2, 0, 'Orange')
console.log(fruits) // ['Apple', 'Banana', 'Orange', 'Cherry']

1.4 객체

1)
const userAge = {
  // key: value
  name: 'Heropy',
  age: 85
}
const userEmail = {
  name: 'Heropy',
  email: 'thesecon@gmail.com'
}

const target1 = Object.assign(userAge, userEmail)
console.log(target1) // {name: 'Heropy', age: 85, email: 'thesecon@gmail.com'}
console.log(userAge) // {name: 'Heropy', age: 85, email: 'thesecon@gmail.com'}
console.log(target1 === userAge) // true

// 원본 데이터 손상 X
const target2 = Object.assign({}, userAge, userEmail)
console.log(target2) // {name: 'Heropy', age: 85, email: 'thesecon@gmail.com'}
console.log(userAge) // {name: 'Heropy', age: 85}
console.log(target2 === userAge) // false

const target3 = Object.assign({}, userAge)
console.log(target3) // {name: 'Heropy', age: 85}
console.log(userAge) // {name: 'Heropy', age: 85}
console.log(target3 === userAge) // false

const a = { k: 123 }
const b = { k: 123 }
console.log(a === b) // false

2)
const user = {
  // key: value
  name: 'Heropy',
  age: 85,
  email: 'thesecon@gmail.com'
}

const keys = Object.keys(user)
console.log(keys) // ['name', 'age', 'email']

// 객체데이터의 인덱싱 방법: XXX['key']
console.log(user.email) // thesecon@gmail.com

const values = keys.map(key => user[key])
console.log(values) // ['Heropy', 85, 'thesecon@gmail.com']

1.5 구조 분해 할당

const user = {
  // key: value
  name: 'Heropy',
  age: 85,
  email: 'thesecon@gmail.com'
}
const { name: heropy, age, email, address = 'Korea' } = user
// E.g, user.address

console.log(`사용자의 이름은 ${heropy}입니다.`) // 사용자의 이름은 Heropy입니다.
console.log(`${heropy}의 나이는 ${age}세입니다.`) // Heropy의 나이는 85세입니다.
console.log(`${heropy}의 이메일 주소는 ${email}입니다.`) // Heropy의 이메일 주소는 thesecon@gmail.com입니다.
console.log(address) // Korea

1.5.1 배열데이터 구조 분해 할당

const fruits = ['Apple', 'Banana', 'Cherry']
const [, b, c, d] = fruits // , 있어야함
console.log(b, c, d) // Banana Cherry undefined

1.6 전개 연산자

const fruits = ['Apple', 'Banana', 'Cherry', 'Orange']
console.log(fruits) // ['Apple', 'Banana', 'Cherry']
console.log(...fruits) // Apple Banana Cherry

function toObject(a, b, ...c) {
  return {
    a: a, 
    b: b, 
    c: c 
  }
}

// 축약 
const toObject= (a, b, ...c) => ({a, b, c })

console.log(toObject(...fruits)) // {a: 'Apple', b: 'Banana', c: Array(2)}

1.7 불변성

  • 원시 데이터: String, Number, Boolean, undefined, null
  • 참조형 데이터: Object, Array, Function

1.7.1 원시 데이터

불변성이 있다.

let a = 1 // 1번 메모리
let b = 4 // 2번 메모리
console.log(a, b, a === b) // 1 4 false
b = a // b에게 1번 메모리 주소를 줌
console.log(a, b, a === b) // 1 1 true
a = 7 // 3번 메모리
console.log(a, b, a === b) // 7 1 false
let c = 1 // 1번 메모리
console.log(b, c, b === c) // 1 1 true

1.7.2 참조형 데이터

불변성이 없다. = 가변성

let a = { k: 1 } // 1번 메모리
let b = { k: 1 } // 2번 메모리
console.log(a, b, a === b) // {k: 1} {k: 1} false
a.k = 7
b = a // b에게 1번 메모리 주소를 줌
console.log(a, b, a === b) // {k: 7} {k: 7} true
a.k = 2
console.log(a, b, a === b) // {k: 2} {k: 2} true
let c = b // c에게 1번 메모리 주소를 줌
console.log(a, b, c, a === c) // {k: 2} {k: 2} {k: 2} true
a.k = 9
console.log(a, b, c, a === c) // {k: 9} {k: 9} {k: 9} true

1.8 얕은 복사와 깊은 복사

import _ from 'lodash'

const user = {
  name: 'Heropy',
  age: 85,
  emails: ['thesecon@gmail.com']
}

1.8.1 얕은 복사 방법1

const copyUser = Object.assign({}, user) 

1.8.2 얕은 복사 방법2

const copyUser = {...user}
console.log(copyUser === user) // false

user.age = 22
console.log('user', user) // user {name: 'Heropy', age: 22, email: 'thesecon@gmail.com'}
console.log('copyUser', copyUser) // copyUser  {name: 'Heropy', age: 85, email: 'thesecon@gmail.com'}

user.emails.push('neo@zillinks.com')
console.log(user.emails === copyUser.emails) // true
console.log('user', user) // user {name: 'Heropy', age: 85, emails: Array(2)}
console.log('copyUser', copyUser) // copyUser  {name: 'Heropy', age: 22, emails: Array(2)}

1.8.3 깊은 복사 방법

const copyUser = _.cloneDeep(user)
console.log(copyUser === user) // false

user.age = 22
console.log('user', user) // user {name: 'Heropy', age: 22, emails: Array(1)}
console.log('copyUser', copyUser) // copyUser {name: 'Heropy', age: 85, emails: Array(1)}

user.emails.push('neo@zillinks.com')
console.log(user.emails === copyUser.emails) // false
console.log('user', user) // user {name: 'Heropy', age: 22, emails: Array(2)}
console.log('copyUser', copyUser) // copyUser {name: 'Heropy', age: 85, emails: Array(1)}

2. JS 데이터 실습

2.1 가져오기, 내보내기

import _ from 'lodash' // From `node_modules`!
import getType from './getType' // getType.js
import { random, user as heropy } from './getRandom' // getRandom.js
import * as R from './getRandom' // 모든 export 가져오기

console.log(_.camelCase('the hello world')) // theHelloWorld
console.log(getType([1, 2, 3])) // Array
console.log(random(), random())
console.log(R) // {name: 'HEROPY', age: 85}

// default export(기본통로)는 
// 이름을 지정할 필요도 없고 활용할때 이름을 언제든지 바꿔도 된다.
// 한 모듈에서 한번만 사용가능하다.
// named export와 같은 모듈에서 사용 가능하다.

// named export는 이름을 지정해야하며 {}를 사용하여 가져와야한다.

2.2 Lodash 사용법

1)
import _ from  'lodash'

const usersA = [
  { userId: '1', name: 'HEROPY' },
  { userId: '2', name: 'Neo' },
]
const usersB = [
  { userId: '1', name: 'HEROPY' },
  { userId: '3', name: 'Amy' },
]
const usersC = usersA.concat(usersB)
console.log('concat', usersC)
// 0: {userId: '1', name: 'HEROPY'}
// 1: {userId: '2', name: 'Neo'}
// 2: {userId: '1', name: 'HEROPY'}
// 3: {userId: '3', name: 'Amy'

// 배열 데이터가 하나 일때 고유화 처리 => uniqBy)
console.log('uniqBy', _.uniqBy(usersC, 'userId')) // 두번째 인수: 고유값으로 사용할 속성의 이름
// 0: {userId: '1', name: 'HEROPY'}
// 1: {userId: '2', name: 'Neo'}
// 2: {userId: '3', name: 'Amy'}

// 배열 데이터가 여러가 일때 고유화 처리 => unionBy)
const usersD = _.unionBy(usersA, usersB, 'userId')
console.log('unionBy', usersD)
// 0: {userId: '1', name: 'HEROPY'}
// 1: {userId: '2', name: 'Neo'}
// 2: {userId: '3', name: 'Amy'}

2)
import _ from  'lodash'

const users = [
  { userId: '1', name: 'HEROPY' },
  { userId: '2', name: 'Neo' },
  { userId: '3', name: 'Amy' },
  { userId: '4', name: 'Evan' },
  { userId: '5', name: 'Lewis' },
]

const foundUser = _.find(users, { name: 'Amy' })
const foundUserIndex = _.findIndex(users, { name: 'Amy' })
console.log(foundUser) // {userId: '3', name: 'Amy'}
console.log(foundUserIndex) // 2

_.remove(users, { name: 'HEROPY' })
console.log(users)
// 0: {userId: '2', name: 'Neo'}
// 1: {userId: '3', name: 'Amy'}
// 2: {userId: '4', name: 'Evan'}
// 3: {userId: '5', name: 'Lewis'}

2.3 JSON

자바스크립트의 객체 표기법

import myData from './myData.json'

const user = {
  name: 'HEROPY',
  age: 85,
  email: [
    'thesecon@gmail.com',
    'neo@zillinks.com'
  ],
}
console.log('user', user) // user {name: 'HEROPY', age: 85, email: Array(2)}

const str = JSON.stringify(user)
console.log('str', str) // str {"name":"HEROPY","age":85,"email":["thesecon@gmail.com","neo@zillinks.com"]}
console.log(typeof str) // string

const obj = JSON.parse(str) 
console.log('obj', obj) // obj {name: 'HEROPY', age: 85, email: Array(2)}
console.log(typeof obj) // object

2.4 Strorage

1)
const user = {
  name: 'HEROPY',
  age: 85,
  email: [
    'thesecon@gmail.com',
    'neo@zillinks.com'
  ],
}

localStorage.setItem('user', JSON.stringify(user)) 
// JSON.stringify(): 자바스크립트 객체 데이터를 문자 데이터화 시킴
console,console.log(JSON.parse(localStorage.getItem('user')));
// JSON.parse(): 문자 데이터를 객체데이터화 시킴
localStorage.removeItem('user') // 로컬스토리지에 데이터 삭제

2) 데이터 갱신
const str = localStorage.getItem('user')
const obj = JSON.parse(str)
obj.age = 22
console.log(obj)
localStorage.setItem('user', JSON.stringify(obj))

3) lodash 패키지에 있는 lowdb를 활용할 수도있다.

2.5 OMBb API

Query String
주소?속성=값&속성=값&속성=값

$ npm i axios
$ npm dev run
import axios from 'axios'

function fetchMovies() {
  axios
  .get('https://www.omdbapi.com/?apikey=7035c60c&s=frozen')
  .then(res => {
    console.log(res)
    const h1El = document.querySelector('h1')
    const imgEl = document.querySelector('img')
    h1El.textContent = res.data.Search[0].Title
    imgEl.src = res.data.Search[0].Poster
  })
}
fetchMovies()

3. 정규표현식(RegExp)

정규식, Regular Expression

3.1 역할

  • 문자 검색(search)
  • 문자 대체(replace)
  • 문자 추출(extract)

3.2 테스트 사이트

https://regexr.com/


3.3 정규식 생성

// 생성자
new RegExp('표현', '옵션')
new RegExp('[a-z]', 'gi')

// 리터럴
/표현/옵션
/[a-z]/gi

3.4 예제 문자

const str = `
010-1234-5678
thesecon@gmail.com
https://www.omdbapi.com/?apikey=7035c60c&s=frozen
The quick brown fox jumps over the lazy dog.
abbcccdddd
`

3.5 메소드

메소드문법설명
test정규식.test(문자열)일치 여부(Boolean) 반환
match문자열.match(정규식)일치하는 문자의 배열(Array) 반환
replace문자열.replace(정규식,대체문자)일치하는 문자를 대체

3.6 플래그(옵션)

플래그설명
g모든 문자 일치(global)
i영어 대소문자를 구분 않고 일치(ignore case)
m여러 줄 일치(multi line)

3.7 패턴(표현)

패턴설명
^ab줄(Line) 시작에 있는 ab와 일치
ab$줄(Line) 끝에 있는 ab와 일치
.임의의 한 문자와 일치
a|ba 또는 b와 일치
ab?b가 없거나 b와 일치
{3}3개 연속 일치
{3,}3개 이상 연속 일치
{3,5}3개 이상 5개 이하(3~5개) 연속 일치
[abc]a 또는 b 또는 c
[a-z]a 부터 z 사이의 문자 구간에 일치(영어 소문자)
[A-Z]A 부터 Z 사이의 문자 구간에 일치(영어 대문자)
[0-9]0 부터 9 사이의 문자 구간에 일치(숫자)
[가-힣]가 부터 힣 사이의 문자 구간에 일치(한글)
\w63개 문자(Word, 대소영문52개 + 숫자10개 + _)에 일치
\b63개 문자에 일치하지 않는 문자 경계(Boundary)
\d숫자(Digit)에 일치
\s공백(Space, Tab 등)에 일치
(?=)앞쪽 일치(Lookahead)
(?<=)뒤쪽 일치(Lookbehind)
profile
front-end developer dreamer

0개의 댓글