import: javascript파일은 기본적으로 외부에 있는 다른 javascript파일을 가져올 수 있는 하나의 통로가 있다. 이를 import로 작성하여 가져온다.
export: javascript파일은 특정 내용을 밖으로 내보낼 수 있는 2개의 통로를 가지고 있다.
module.js : 내보내는(export) 코드만 존재하여 사용할 수 있는 파일이며 아래의 js파일들이 그 예시이다.
Default export: 이름 지정 필요 없음, export와 default키워드를 사용한다.import시 다른 이름으로 지정해서 사용해도 상관 없다.
기본 통로이며 하나의 모듈에서 하나의 데이터만 내보내기 가능하다.
// getType.js, 기본통로,
export default function (data) {
return Object.prototype.toString.call(data).slice(8, -1);
}
// getRandom.js
export function random() {
return Math.floor(Math.random() * 10)
}
export const user = {
name: 'Hun',
age: 27
}
위의 getType.js와 getRandom.js를 이용하여 예시를 보자.
// lodash
import _ from 'lodash' // From `node_modules`!
//_: default export, 이름 자유롭게 사용가능
console.log(_.camelCase('the hello world')) // theHelloWorld, lodash
// getType.js
import checktype from '../javascriptEssentials/getType' // getType.js
console.log(checktype([1, 2, 3])) // Array
// getRandom.js
// 1. 일반적인 import 방식
import random from '../javascriptEssentials/getRandom' // getRandom.js
console.log(random(), random()) // 4 7
// 2. import시 as를 사용한 경우
import {random, user as Hun} from '../javascriptEssentials/getRandom' // getRandom.js
console.log(Hun) // {name: "Hun", age: 27}
// 3. import시 객체분해구조를 사용한 경우
import {random, user} from '../javascriptEssentials/getRandom' // getRandom.js
console.log(user) // {name: "Hun", age: 27}
// 4. random과 user 한번에 꺼내오기 *(와일드 카드)사용
import * as R from '../javascriptEssentials/getRandom' // getRandom.js
console.log(R) // {user:{...}, random, default:123}
// Named export와 default export는 같이 사용할 수 있다.
export default 123
lodash가 제공하는 함수 기능 몇가지를 알아보자!
// lodash 함수
import _ from 'lodash' // _ : default export, 이름 자유롭게 사용가능
const usersA = [
{ userId: '1', name: 'Hun'},
{ userId: '2', name: 'toffg'}
]
const usersB = [
{ userId: '1', name: 'Hun'},
{ userId: '3', name: 'Amy'}
]
const usersC = usersA.concat(usersB);
console.log('concat: ', usersC);
// concat : [
// { userId: '1', name: 'Hun'},
// { userId: '2', name: 'toffg'},
// { userId: '1', name: 'Hun'},
// { userId: '3', name: 'Amy'}
// ]
이미 중복이 발생한 배열 데이터에서 중복을 제거하기 위해 사용하는 메소드이다.
uniqBy(중복된 데이터가 있는 배열 데이터, 중복을 구분할 고유의 속성)
console.log('uniqBy: ', _.uniqBy(usersC, 'userId'));
// uniqBy : [
// { userId: '1', name: 'Hun'},
// { userId: '2', name: 'toffg'},
// { userId: '3', name: 'Amy'}
// ]
중복이 발생할 수 있는 배열 데이터들을 합치기 전에 사용하는 메소드이다.
const usersD = _.unionBy(usersA, usersB, 'userId');
console.log('unionBy: ', usersD);
// unionBy : [
// { userId: '1', name: 'Hun'},
// { userId: '2', name: 'toffg'},
// { userId: '3', name: 'Amy'}
// ]
원하는 조건의 객체 데이터를 찾을 때 사용하는 메소드이다.
find(배열데이터, 조건)
const users = [
{ userId: '1', name: 'Hun'},
{ userId: '2', name: 'toffg'},
{ userId: '3', name: 'Amy'},
{ userId: '4', name: 'Evan'},
{ userId: '5', name: 'Luminus'}
]
const foundUser = _.find(users, { name: 'Amy'})
console.log(foundUser); // { userId: '3', name: 'Amy'}
해당 조건의 객체 데이터를 찾아 index번호를 반환하는 메소드이다.
findIndex(배열데이터, 조건)
const users = [
{ userId: '1', name: 'Hun'},
{ userId: '2', name: 'toffg'},
{ userId: '3', name: 'Amy'},
{ userId: '4', name: 'Evan'},
{ userId: '5', name: 'Luminus'}
]
const foundUserIndex = _.findIndex(users, { name: 'Amy'})
console.log(foundUserIndex); // 2
해당 조건의 객체 데이터를 찾아 삭제하는 메소드이다.
remove(배열데이터, 조건)
_.remove(users, { name: 'Amy'});
console.log(users)
// [
// { userId: '1', name: 'Hun'},
// { userId: '2', name: 'toffg'},
// { userId: '4', name: 'Evan'},
// { userId: '5', name: 'Luminus'}
// ]
JSON (JavaScript Object Notation):
javascript의 객체 표기법으로 속성-값 쌍 또는 키-값 쌍 으로 이루어진 데이터 오브젝트를 전달하기 위해 인간이 읽을 수 있는 텍스트를 사용하는 개방형 표준 포맷, 서버와의 통신을 주고받는 하나의 포맷이다.
말이 어려운데 키-값 쌍으로 이루어진 데이터 오브젝트라고 생각하자.
// myData.json
{
"name": "Hun",
"age": 27,
"emails": [
"rk645046@gmail.com",
"toffg6450@naver.com"
]
}
JSON은 문자 데이터이다. import로 가져오면 객체데이터처럼 사용되는 것을 볼 수 있다.
// main.js
import myData from './myData.json'
console.log(myData);
// {
// "name": "Hun",
// "age": 27,
// "emails": [
// "rk645046@gmail.com",
// "toffg6450@naver.com"
// ]
// }
JSON.stringify( ): 특정 데이터를 JSON포맷으로 문자데이터화 시켜주는 메소드이다.
JSON.parse( ): 데이터를 javascript데이터처럼 변경시키는 메소드이다.
const user = {
name: 'Hun',
age: 27,
emails: [
'rk645046@gmail.com',
'toffg6450@naver.com'
]
}
console.log('user', user);
// { name: 'Hun',
// age: 27,
// emails: Array(2)
// }
const str = JSON.stringify(user);
console.log('str', str);
// str
// {
// "name": "Hun",
// "age": 27,
// "emails": [
// "rk645046@gmail.com",
// "toffg6450@naver.com"
// ]
// }
console.log(typeof str); // string
const obj = JSON.parse(str);
console.log('obj', obj);
// objㄴ
// { name: 'Hun',
// age: 27,
// emails: Array(2)
// }
Storage: 저장소
브라우저에서 개발자 도구를 열고 Application탭을 눌러 Storage에 접근을 하면 localStorage 등을 확인할 수 있다.
const user = {
name: 'Hun',
age: 27,
emails: [
'rk645046@gmail.com',
'toffg6450@naver.com'
]
}
key-value형태로 데이터로 저장하고 value는 문자 데이터로 저장해야한다.
// value를 문자 데이터로
localStorage.setItem('user', JSON.stringify(user));
데이터를 읽어오는 용도, key값만 적어서 사용한다.
문자 데이터 -> 객체 데이터(javascript데이터)로 변환시켜준다.
console.log(JSON.parse(localStorage.getItem('user')));
//{ name: "Hun",
// age: 27,
// emails: Array(2)
// }
데이터를 삭제하는 용도, key값만 적어서 사용한다.
localStorage.removeItem('user'); // Local Storage에서 제거됨, console에는 남음
위의 코드에서 removeItem()부분을 주석 처리하고 다시 실행 시키면 Local Storage에 데이터가 남아있다.
이 데이터를 가지고 와서 수정을 해보자!
const str = localStorage.getItem('user');
const obj = JSON.parse(str);
console.log(obj);
//{ name: "Hun",
// age: 27,
// emails: Array(2)
// }
obj.age = 22;
console.log(obj);
//{ name: "Hun",
// age: 22,
// emails: Array(2)
// }
localSotrage에 데이터를 수정하기위해서는 데이터를 가져와서 코드 내에서 수정하고 다시 해당하는 key의 이름으로 덮어쓰기를 해주면 된다.
localStorage.setItem('user', JSON.stringify(obj));
The Open Movie Database의 약어로 영화 검색을 하는 API이다.
주소?속성=값&속성=값&속성=값
주소?apiKey=Key&s=movieName&
OMDb API를 사용해보기 위해 axios 패키지를 npm i axios
로 설치해준다.
import axios from 'axios'
function fetchMovies() {
// get(): 해당 페이지에 접근
// then(): 처리
axios
.get('https://www.omdbapi.com/?apikey=7035c60c&s=frozen')
.then(res => {
console.log(res); // 해당 url에서 나온 데이터가 출력됨
// 데이터를 이용한 출력
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();
※ apikey는 따로 발급을 받아야 하며 여기서는 'HEROPY'님의 apikey를 사용했음을 알립니다.
https://heropy.blog/