[패스트캠퍼스] 프론트엔드 강의 종합반 week 7 JavaScript Level Up

청수동햄주먹·2023년 2월 2일
0

JS data

String: "", '', ``

모를 땐 string mdb 검색해서 공부해보기

String.prototype.indexOf('단어')

문자열에 단어가 있으면 단어가 시작되는 인덱스 리턴, 존재하지 않으면 -1

String.prototype.slice(beginIndex, endIndex)

endIndex 직전까지만 추출

String.prototype.replace('바꾸고 싶은 부분','대체 문자')

String.prototype.match(정규표현식)

정규표현식을 통해서 문자열 추출

const str = 'thesecond@gmail.com
console.log(str.match(/.+(?=@)/)[0]) 
// @ 앞은 전부 출력
// thesecond

String.prototype.trim()

연결된 공백을 없애준다

Number

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

const integer = parseInt(str) // 3
const float = parseFloat(str) // 3.14
console.log(typeof integer, typeof float) // number number

Math.abs()

주어진 숫자의 절대값을 반환

Math.min() Math.max()

최소값, 최대값 반환

Math.ceil() Math.floor() Math.round()

올림, 내림, 반올림

Math.random()

배열

Array.prototype.length

아이템의 갯수를 알 수 있다

Array.prototype.forEach(콜백함수)

const fruits = ['apple','banana','cherry']

fruits.forEach((fruit, i) => {
  console.log(fruit, i)
})
// apple 0
// banana 1
// cherry 2

Array.prototype.map(콜백함수)

리턴된 데이터를 새로운 어레이로 반환할 수 있다.

const fruits = ['apple','banana','cherry']

const basket = fruits.map((fruit, i) => {
  return {
    id: i,
    name: fruit
  }
})
console.log(basket)
// [{id: 0, name: "apple"}, {id: 1, name: "banana"}, {id: 2, name: "cherry"}]

Array.prototype.filter()

const numbers = [1,2,3,4]
const a = numbers.map(number => {
  return number < 3
})
console.log(a) // [true, true, false, false] 

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

Array.prototype.find(조건)

조건을 만족하는 첫번째 요소의 값 반환

const a = fruits.find(fruit => {
  return /^B/.test(fruit) // B로 시작하는
})
console.log(a) // Banana

const B = fruits.findIndex(fruit => {
  return /^B/.test(fruit) // B로 시작하는
})
console.log(b) // 1

Array.prototype.includes()

boolean 반환

Array.prototype.splice()

특정한 인덱스의 아이템을 삭제하거나 삽입. 원본을 수정한다.

  • .splice(2, 1)
    인덱스번호 2번에서 아이템 1개를 지운다
  • .splice(2,0,999)
    인덱스번호 2번에서 아이템 0개를 지우고 999를 추가한다

객체 Object

[]. 정적메소드

Object.assign(target, sources, ...)

하나 이상의 출처 객체로부터 대상 객체로 속성을 복사할 때

const fruitBox = {
  name: 'apple',
  amount: 3
}
const fruitFarmer = {
  name: 'apple',
  farmer: 'steve'
}
const target = Object.assign(fruitBox, fruitFarmer)

console.log(target) // { name: 'apple', amount: 3, farmer: 'steve' }
console.log(fruitBox) // { name: 'apple', amount: 3, farmer: 'steve' }
console.log(target === fruitBox) // true
// 같은 주소를 참조하고 있기 때문에

const newTarget = Object.assign({},fruitBox, fruitFarmer)
console.log(newTarget) // { name: 'apple', amount: 3, farmer: 'steve' }
console.log(newTarget === fruitBox) // false
// {}을 넣으므로써 아예 새로운 메모리 주소를 할당하게 된 것.

const a = { k: 123 }
const b = { k: 123 }

console.log(a === b) // false
// 다른 메모리 주소를 참조하고 있기 때문에

Object.keys()

const keys = Object.keys(target)
console.log(keys) // [ 'name', 'amount', 'farmer' ]
console.log(tartet['name']) // apple

const values = keys.map(key => target[key])
console.log(values) // [ 'apple', 3, 'steve' ]

구조 분해 할당 Destructuring assignment

비구조화 할당

  • 필요한 요소만 꺼내서 사용할 수 있다.
  • 변수명으로 바로 사용이 가능하다. 다만 순서대로 꺼내오기
  • 기본값을 설정해서 활용해줄수도 있다(undefined를 피함). 자주 사용되지 않지만 가끔씩 필요
const apple = { name: 'apple', amount: 3, farmer: 'steve' }
const { name, amount, farmer, address='korea' } = apple // apple 복사

console.log(address) // korea
console.log(telephone) // error!
console.log(apple.telephone) // undefined

전개 연산자 Spread ...rest parameter

const fruits = ['apple', 'banana', 'cherry']
console.log(...fruits) // apple banana cherry

function toObject = (a,...b) => ({
    a : a, 
    b // 속성명과 변수의 이름이 같을 때 하나만 써도 됨
}) // 화살표 함수에서 객체 데이터 반환할 때는 (안에)
console.log(toObject(...fruits)) // { a: 'apple', b: [ 'banana', 'cherry' ] }

불변성 Immutability

원시 데이터 (기본 데이터)

String, Number, Boolean, undefined, null

//----------------------------------------------------
//|1:    1      |2:     4     |3:    7      |4:         
//----------------------------------------------------

// 1
let a = 1
let b = 4
console.log( a === b ) // false
// 2
b = a
console.log( a === b ) // true
// 3
a = 7
console.log( a === b ) // false
// 4
let c = 1
console.log( b === c ) // true
// 5
let d = 4
  1. a 는 1번 주소를 가리키고 b 는 2번 주소를 가리킴
  2. b 도 1번 주소를 가리킴
  3. 7은 새로운 데이터 이므로 3번 주소로. a 는 3번 을 가리킴
  4. c 는 1번 주소를 가리킴
  5. d 는 2번 주소를 가리킴

원시데이터를 가리킬 때는 메모리 주소까지 생각할 필요는 없음!
-> 따라서 생김새가 다르면 다른 주소에 저장 되어 있다는 뜻
원시데이터는 한번 만들어지면 불변하기 때문에 변수가 가리키는 주소만 달라짐.

참조형 데이터

  • Object, Array, Function
  • 새로운 데이터를 만들 때마다 그 안의 값이 같더라도 새로운 메모리 주소에 저장된다
  • 불변성이 없음! 가변
//----------------------------------------------------
//|1: {  k: 1 }  |2: {  k: 1 }  |3: {       }  |4:         
//----------------------------------------------------

// 1
let a = { k: 1 }
let b = { k: 1 }
console.log(a===b) // false
// 2
a.k = 7
b = a
console.log(a===b) // true
// 3
a.k = 2
console.log(a===b) // true
// 4
a.k = 9
let c = b
console.log(a===c) // true
  1. a 와 b는 서로 다른 주소를 바라보고 있다
  2. b 가 a와 같은 주소를 바라보고 있음 k = 7
  3. b 가 a와 같은 주소를 바라보고 있음 k = 2
  4. c, b 가 a와 같은 주소를 바라보고 있음 k = 9

따라서 a, b를 별개로 구분해서 관리하고 싶다면 깊은 복사라는 개념을 사용 해야 한다

얕은 복사 shallow copy

표면만 복사. 원본이 수정되면 복사본도 수정된다

const fruit = { name: 'apple', amount: 3, farmer: ['steve'] }
const copyFruit = {...fruit} // 전개해서 복사 { name: 'apple', amount: 3, farmer: 'steve' }
console.log(fruit === copyFruit) // false

fruit.amount = 7
console.log(fruit) // { name: 'apple', amount: 7, farmer: 'steve' }
console.log(copyFruit) // { name: 'apple', amount: 3, farmer: 'steve' }

fruit.farmer.push('pooh') // ['steven', 'pooh']
console.log(fruit.farmer === copyFruit.farmer) // true

깊은 복사 deep copy

내부의 모든 참조까지 복사

  • _.cloneDeep()
import _ from 'lodash'
const fruit = { name: 'apple', amount: 3, farmer: ['steve'] }
const copyFruit = _.cloneDeep(user)
console.log(fruit === copyFruit) // false

fruit.amount = 7
console.log(fruit) // { name: 'apple', amount: 7, farmer: 'steve' }
console.log(copyFruit) // { name: 'apple', amount: 3, farmer: 'steve' }

fruit.farmer.push('pooh') // ['steven', 'pooh']
console.log(fruit.farmer === copyFruit.farmer) // false
  • _.cloneDeep
    재귀적으로 값을 복사한다. (값마다 새로운 메모리 주소 할당)

JS data practices

가져오기, 내보내기

  • export default 기본통로로 나간다.
    • export default function {} 이름 지정 필요 없음.
    • import 할 때 내가 원하는 이름 지정 가능
      ex:) import checkType from './getType'
  • export 이름을 지정해줘야 내보낼 수 있다.
    • export function random() {}
    • { 이름 } 으로 import 한다. 부르고 싶은 이름으로 바꿀 수 있다
      ex:) import {random as example} from './getRandom'
  • import * as R from './getRandom'
    모든 구성요소들을 가져온다
    • wildcard character: 여러 내용을 한꺼번에 지정할 수 있다

Lodash 사용법

_.uniq(array)

배열 데이터안의 중복되는 값들을 고유하게 바꿔준다

import _ from 'lodash'

const boxA = [
  { id: '1', name: 'apple' },
  { id: '2', name: 'banana' }
]
const boxB = [
  { id: '1', name: 'apple' },
  { id: '3', name: 'cherry' }
]

const boxC = boxA.concat(boxB)
console.log(boxC)

console.log(_.uniqBy(boxC), 'id')

const boxD = _.unionBy(boxA,boxB, 'id')
console.log(boxD)
  • boxA.concat(boxB)
    • 두개의 데이터를 합쳐서 반환
    • [{id: "1", name: "apple"}, {id: "2", name: "banana"}, {id: "1", name: "apple"}, {id: "3", name: "cherry"}]
  • _.uniqBy(boxC), 'id'
    • 배열데이터 1개의 id 기준으로 각 id당 한 객체
    • [{id: "1", name: "apple"}, {id: "2", name: "banana"}, {id: "3", name: "cherry"}]
  • _.unionBy(boxA,boxB, 'id')
    • 배열데이터 여러개의 id 기준으로 각 id당 한 객체
    • [{id: "1", name: "apple"}, {id: "2", name: "banana"}, {id: "3", name: "cherry"}]

_.find()

배열데이터에서 데이터를 찾아준다
const foundUser = _.find(users, {name: 'Amy'})
> {userId: "3", name:"Amy"}

_.findIndex()

배열데이터에서 데이터의 인덱스를 찾아준다
const foundUser = _.findIndex(users, {name: 'Amy'})
> 2

.remove()

배열 데이터에서 해당 객체데이터 제거

JSON JavaScript Object Notation

  • 속성-값 쌍으로 이루어진 데이터 오브젝트를 전달하기위한 개방형 표준 포맷
  • 비동기 브라우저/서버통신(ajax)를 위한 주요 데이터 포맷
  • 변수값을 표현하는데 적합하다
  • 프로그램 언어나 플랫폼에 독립적이다
  • 큰따옴표만 허용 ""
//myData.json
{
  "string": "button",
  "number": 123,
  "boolean": true,
  "null": null,
  "object": {},
  "array": [],
  "undefined": undefined, // error!
}
import myData from './myData.json'

console.log(myData) // 객체 데이터처럼 사용이 된다

JSON.stringfy(변수)

  • 큰 덩어리의 문자데이터화(제이슨포맷) 시켜준다.

JSON.parse(제이슨포맷)

  • 제이슨 포맷을 객체데이터로 바꿔준다

Storage

  • 로컬 스토리지는 하나의 사이트에 종속이 된다
const fruit = {
  name: 'apple',
  price: 3,
  rank: ['A+','B']
}
localStorage.setItem('fruit', JSON.stringify(fruit))
const str = localStorage.getItem('fruit')
const obj = JSON.parse(str)
obj.price = 5 // 가격 변경
localStorage.setItem('fruit',JSON.stringify(obj)) // 덮어쓰기
localStorage.removeItem('fruit')

localStorage.setItem('key','value')

localStorage.getItem('key')

localStorage.removeItem('key')

lodash

lowdb 검색 -> 깃헙 저장소 이동

  • npm install lowdb

OMDb API

omdb
사용자 인증해야 api 키를 받을 수 있다.

쿼리 스트링 Query String

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

ex:) https:\//www.omdbapi.com/?apikey=[yourkey]&s=frozen

axios 검색 -> 깃헙 저장소 이동

  • npm i axios
  • "dependencies"에 axios 확인

practice

import axios from 'axios'

function fetchMovies() {
  axios
    .get('https://www.omdbapi.com/?apikey=yourkey&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()

profile
코딩과 사별까지

0개의 댓글