rest와 spread는 다른 것
The Arguments Object - 인수객체 - 유사 배열 객체
모든 함수에서 사용 가능하다
array 같은 object다
길이를 가지고 있고 인덱스도 가지고 있다.
push/pop과 같은 배열 메소드는 가지고 있지 않다.
arrow function에서는 사용이 불가능하다.
인수객체는 함수로 전달된 인수를 모두 가지고 있다.
function sumAll(){
let total = 0;
//argument = 8, 3, 2, 1 4개를 가지고 있는 것임
for(let i=0; i<arguments.length;i++){
total += arguments[i];
}
return total
}
console.log(sumAll(8, 3, 2, 1));
console.log(sumAll(...[8, 3, 2, 1]));
function sum(){
console.log(arguments); // [Arguments] { '0': 1, '1': 2, '2': 3, '3': 4, '4': 5 }
함수를 실행하면서 전달받은 arguments들이 순서가 키값 값들이 밸류값으로 오브젝트로 나오는 걸 알 수 있다.
}
sum(1,2,3,4,5)
argument는 배열이 아니기 때문에 pop/push/reduce/map 이러한 배열 메소드를 사용하지 못함
그래서 spread문법을 사용해서 전달받은 arguments들을 spread해줌
function sum1(...nums){
//parameter에 ...nums을 해줘서 전달받은 인자들을 모아준 거임
console.log(nums); // [ 1, 2, 3, 4, 5 ]
}
function sum2(a,b,...nums){
//parameter에 ...nums을 해줘서 전달받은 인자들을 모아준 거임
console.log(nums); //a,b를 제외한 나머지 것들이 nums에 담김 [ 3, 4, 5 ]
console.log(a); //1
console.log(b); //2
}
sum1(1,2,3,4,5);
sum2(1,2,3,4,5);
짧고 빠른 문법
배열에 있는 값,오브젝트에 있는 프로퍼티들을 해체해서 별개의 변수형태로 만듦
const raceResults = ['lee', 'kim', 'hwang'];
//[ ]안에 사용할 변수명 사용할 배열
//배열의 순서대로 변수명 순서로 담김
const [gold, silver, bronze] = raceResults;
console.log(gold); // 'lee'
console.log(silver); // 'kim'
console.log(bronze); // 'hwang'
const [fastest, ...everyonElse] = raceResults;
console.log(fastest); // 'lee'
console.log(everyonElse ); //spead를 사용하면 배열에 담김 ['kim', 'hwang']
const scores = [100,98,96,70,80,60,70];
const highScore = scores[0];
const secondeHighScore = scores[1];
//분해구조를 이용해서 더 간편하게
const scores2 = [100,98,96,70,80,60,70];
//순서를 기반으로 할당됨
const [highScore2, secondeHighScore2] = scores2
순서를 따르지 않기 때문에 배열 구조분해보다 실용적이다.
키값을 변수명으로 property를 value값으로
let first = runner.first <<<<<이거랑 똑같음
//객체 분해구조
const runner ={
first:'eliud',
last:'kipchoge',
country:'kenya',
title:'elder of the order of the golden heart of kenya',
}
//객체의 키값을 변수명으로 사용할 오브젝트
const {first, last, country,d} = runner;
console.log(first); //eliud
console.log(last); // kipchoge
console.log(country); // kenya
//객체에 d라는 키값이 없기 때문에 undefined
console.log(d); // undefined
const user = {
email:'dkdkdk@naver.com',
password:'sdkfjkdsf',
firstName:'Harvey',
lastName:'Milk',
born:1930,
died:1990,
city:'seoul',
}
//변수를 이용해서 접근
let userName = `${user.firstName} ${user.lastName}`
let userEmail = user.email;
console.log(userName) // 'Harvey'
console.log(userEmail) // 'Milk'
//분해구조를 이용해서 접근
const {firstName, lastName, email, ...other} = user;
console.log(firstName) // 'Harvey'
console.log(lastName) // 'Milk'
console.log(email) // 'dkdkdk@naver.com'
console.log(other); //{ password: 'sdkfjkdsf', born: 1930, died: 1990, city: 'seoul' }
//키값이 아닌 다른 이름의 변수로 저장하는 방법
**배열 안에 키값 : 변수명**
const {born : birthYear, died:deadYear} = user;
console.log(born); // ReferenceError: born is not defined
console.log(birthYear); // 1930
//디폴트값
const user = {
email:'dkdkdk@naver.com',
password:'sdkfjkdsf',
firstName:'Harvey',
lastName:'Milk',
born:1930,
died:1990,
city:'seoul',
}
//user1과 다르게 born, died값이 없을 때
const user2 = {
email:'user2@naver.com',
password:'user2password',
firstName:'user2',
lastName:'userTwo',
city:'seoul',
}
//디폴트값을 설정하는 방법
//오브젝트에 없는 값을 이용할 때
> **키 이름 = '설정할 디폴트 값'**
const {firstName:user2FirstName, lastName:user2LastName, born = '아직 살아 있어요', died} = user2;
console.log(user2FirstName); //user2
console.log(user2LastName); // userTwo
console.log(born); // 아직 살아 있어요
//user2에 died 값이 없기 때문에 undefined가 리턴
console.log(died); // undefined
//만약 값이 있는 오브젝트의 값에 디폴트값을 주면 디폴트값이 아닌 기존의 값이 리턴됨
const {born : birthYear, died='나 안 죽었어'} = user;
console.log(died) // 1990
let obj = {
firstName : 'lee',
lastName : 'hehe',
age : 20,
hobby:'soccer',
height : 172,
}
function fullName(user){
return `${user.firstName} ${user.lastName}`
}
//코드블럭 안쪽에서 분해함
function fullName2(user){
const {firstName, lastName} = user
return `${firstName} ${lastName}`
}
//매개변수에서 분해 바로함
function fullName3({firstName, lastName}){
return `${firstName} ${lastName}`
}
//디폴트값을 줄 수도 있음
function fullName4({firstName, lastName, hello='hi'}){
return `${firstName} ${lastName} ${hello}`
}
//변수명을 바꿀 수도 있음
function fullName5({firstName, lastName:lastName2}){
return `${firstName} ${lastName2}`
}
console.log(fullName(obj)); //lee hehe
console.log(fullName2(obj)); //lee hehe
console.log(fullName3(obj)); //lee hehe
console.log(fullName4(obj)); //lee hehe hi
console.log(fullName5(obj)); //lee hehe
//내부함수에서도 사용가능
const movie = [
{
name: "heh1",
rating: 96,
},
{
name: "heh2",
rating: 80,
},
{
name: "heh3",
rating: 75,
},
{
name: "heh4",
rating: 100,
},
{
name: "heh5",
rating: 70,
},
{
name: "heh6",
rating: 60,
},
];
//이 데이터에서 rating이 80점 이상인 영화만 뽑으면
let result = movie.filter(movie=>movie.rating>=80)
console.log(result);
/*
[
{ name: 'heh1', rating: 96 },
{ name: 'heh2', rating: 80 },
{ name: 'heh4', rating: 100 }
]
*/
//여기서 바로 분해구조로 movie에 rating으로 접근
let result2 = movie.filter(({rating})=>rating>=80);
console.log(result2);
/*
[
{ name: 'heh1', rating: 96 },
{ name: 'heh2', rating: 80 },
{ name: 'heh4', rating: 100 }
]
*/
//여러개 한번에 가능
let result3 = movie.map(({name, rating})=>`${name} ${rating}`);
console.log(result3);//[ 'heh1 96', 'heh2 80', 'heh3 75', 'heh4 100', 'heh5 70', 'heh6 60' ]