모를 땐 string mdb 검색해서 공부해보기
문자열에 단어가 있으면 단어가 시작되는 인덱스 리턴, 존재하지 않으면 -1
endIndex 직전까지만 추출
정규표현식을 통해서 문자열 추출
const str = 'thesecond@gmail.com
console.log(str.match(/.+(?=@)/)[0])
// @ 앞은 전부 출력
// thesecond
연결된 공백을 없애준다
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
주어진 숫자의 절대값을 반환
최소값, 최대값 반환
올림, 내림, 반올림
아이템의 갯수를 알 수 있다
const fruits = ['apple','banana','cherry']
fruits.forEach((fruit, i) => {
console.log(fruit, i)
})
// apple 0
// banana 1
// cherry 2
리턴된 데이터를 새로운 어레이로 반환할 수 있다.
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"}]
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]
조건을 만족하는 첫번째 요소의 값 반환
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
boolean 반환
특정한 인덱스의 아이템을 삭제하거나 삽입. 원본을 수정한다.
[]. 정적메소드
하나 이상의 출처 객체로부터 대상 객체로 속성을 복사할 때
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
// 다른 메모리 주소를 참조하고 있기 때문에
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' ]
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
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' ] }
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: { 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
따라서 a, b를 별개로 구분해서 관리하고 싶다면 깊은 복사라는 개념을 사용 해야 한다
표면만 복사. 원본이 수정되면 복사본도 수정된다
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
내부의 모든 참조까지 복사
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
배열 데이터안의 중복되는 값들을 고유하게 바꿔준다
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)
배열데이터에서 데이터를 찾아준다
const foundUser = _.find(users, {name: 'Amy'})
> {userId: "3", name:"Amy"}
배열데이터에서 데이터의 인덱스를 찾아준다
const foundUser = _.findIndex(users, {name: 'Amy'})
> 2
배열 데이터에서 해당 객체데이터 제거
//myData.json
{
"string": "button",
"number": 123,
"boolean": true,
"null": null,
"object": {},
"array": [],
"undefined": undefined, // error!
}
import myData from './myData.json'
console.log(myData) // 객체 데이터처럼 사용이 된다
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')
lowdb 검색 -> 깃헙 저장소 이동
omdb
사용자 인증해야 api 키를 받을 수 있다.
주소?속성=값&속성=값&속성=값
ex:) https:\//www.omdbapi.com/?apikey=[yourkey]&s=frozen
axios 검색 -> 깃헙 저장소 이동
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()