TIL 102 | Rest Syntax, Spread Syntax, Object Literal

meow·2021년 1월 6일
1

JavaScript

목록 보기
43/46
post-thumbnail

1. Rest Syntax

"I don't know how many vars you are sending, so I'll put whatever else you sent in an array."

arguments 활용

function findHeighest(upperLimit) {
  let max = 0;
  fot(let i = 1; i< arguments.length; i++) {
    if(arguments[i] < upperLimit && arguments[i] > max) {
      max = arguments[i];
    }
  }
  return max;
}

const heighest = findHighest(80, 99, 88, 77, 88, 87, 67, 56, 34, 5, 1)

Rest operator 활용

function findHeighest(upperLimit, ...numList) {
  let max = 0;
  numList.filter(funtion(n) {
                 if((n < upperLimit) && (n > max)){
    			max = n;
  			}
                 })
                 return max;
}

const heighest = findHighest(80, 99, 88, 77, 88, 87, 67, 56, 34, 5, 1)

2. Spread Syntax

"My stuff is already an array. You've got separate params, unpack it."

Ugly Way

function sum(a, b, c, d, e){
  return a + b + c + d + e;
}

const numbers = [1, 2, 3, 4, 5];
const uglyWay = sum(numbers[0], numbers[1], numbers[2], numbers[3], numbers[4]);
console.log(uglyWay);

Old Way

function sum(a, b, c, d, e){
  return a + b + c + d + e;
}

const numbers = [1, 2, 3, 4, 5];
const oldWay = sum.apply(null, numbers);
console.log(oldWay);

Spread Way

function sum(a, b, c, d, e){
  return a + b + c + d + e;
}

const numbers = [1, 2, 3, 4, 5];
const spreadWay = sum(...numbers);
console.log(spreadWay);

리덕스 예시

ugly example

function aReducer(state, action) {
  let newState = Object.assign({}, state);
  newState.newProperty = action.payload;
  console.log(newState);
}

spread example

function aReducer(state, action) {
  let newState = {...state};
  newState.newProperty = action.payload;
  console.log(newState);
}

깊은 복사 예시

let myArr = [1, 2, 3, 4];
let myArr2 = myArr;
myArr2.push(5);
// 주솟값은 바뀌지 않기 때문에 원본인 myArr 도 [1, 2, 3, 4, 5]가 됨

이전 방식

let myArr = [1, 2, 3, 4];
let myArr2 = myArr.slice();
myArr2.push(5);

스프레드 연산자 방식

let myArr = [1, 2, 3, 4];
let myArr2 = [...myArr];
myArr2.push(5);

3. Object Literal

객체를 생성하는 기존의 세가지 방법

let x = new Object(); // {}

let y = Object.create(null); // {}

let z = {
  a: 1	// {a: 1}
}

cool way
구조분해할당

const { name, aMethod } = someJSON;
const { name: teacherName, aMethod: teacherMethod } = someJSON;
console.log(teacherName);
console.log(teacherMethod);

응용하기

// nested objects
const { name: {[0]: firstName, [1]: secondName} } = someJSON;
console.log(firstName);
console.log(secondName);
// nested objects
const [first, second, third] = someJSON.name;
console.log(first);
console.log(second);

// 요건 몰랐네!
const [,,,fourth, fifth] = someJSON.name;
const [, two, ...others] = someJSON.name;

활용 예시

getArea({width: 70, height: 100});

function getArea({width, height}){
  console.log(width * height);
}
profile
🌙`、、`ヽ`ヽ`、、ヽヽ、`、ヽ`ヽ`ヽヽ` ヽ`、`ヽ`、ヽ``、ヽ`ヽ`、ヽヽ`ヽ、ヽ `ヽ、ヽヽ`ヽ`、``ヽ`ヽ、ヽ、ヽ`ヽ`ヽ 、ヽ`ヽ`ヽ、ヽ、ヽ`ヽ`ヽ 、ヽ、ヽ、ヽ``、ヽ`、ヽヽ 🚶‍♀ ヽ``ヽ``、ヽ`、

0개의 댓글