#TIL (May 12th, 스물일곱번째 이야기)

Jung Hyun Kim·2020년 5월 12일
0

자바스크립트 새로운 용어 정리

Default parameters

function multiply(a,b =1) {
return a *b }

if no b is passed in, then b=1 

multiply(8)
//8
multiply(2,8)
//16

const greet = (person, greeting = 'hi') => {
console.log(`${greeting}, ${person}!`) 
}

greet(joanne) 
greet('joanne', 'hi')

//arguments를 여러개 넣을수도 있음, 하지만 순서대로 적용시키는게 매우 중요함! 
const greet =(person, greeting = 'hi', punctuation = '!') => {
console.log(`${greeting}, ${person}! ${punctuation}`) 
}

Spread (three dots...)

  • spread는 []array braket 혹은 일반 STRING을 을 그냥 (,,,)로 처리할수 있게 해줌.
  • interate 하고 결과를 보여줌
  • concat/split 이랑 비슷할 수 있음!
Math.max(3,4,5,6)// 하면 99 출력
const nums = [45,23,34,7,5] 
Math.max(nums)//하면 NaN 출력 됨.. 그래서 이때
Math.max(...nums)//하면 45가 출력됨 

또다른 예를 보자면 
function giveMeFour(a,b,c,d) {
  console.log('a',a)
  console.log('b',b)
  console.log('c',c)
  console.log('d',d)
  
const str ='GOAT'
giveMeFour(...str) 이렇게 출력됨 
/*  a G
  	b O
  	c A
  	d T

결국 */
giveMeFour(...str)
giveMeFour('G','O','A','T') 는 같다! 
  

//또한 array를 합칠수도 있다! 
  
const coffee = ['Americano', 'Latte', 'Mocha']
const tea = ['Earl grey', 'Green Tea']

const drink = [...coffee, ...tea];
  //drink 출력하면 
["Americano", "Latte", "Mocha", "Earl grey", "Green Tea"] //이렇게 나옴! 
  
coffee.concat(tea) //랑 같이 출력 된다고 보면 됨 

"abcdefg".split('');
["a", "b", "c", "d", "e", "f", "g"]

[..."abcdefg"]
["a", "b", "c", "d", "e", "f", "g"] //이렇게 해도 같이 적용된다

//object 안에 있는 key도 가져올수 있음 
  const canine = {
    legs = 4
    furry = true
  }
  
  const dog = {
   ...canine,
   isPet: true,
   adorable: true
 }
 
하면 dog 출력하면 아래와 같이 나옴 
{legs: 4, furry: true, isPet: true, adorable: true}
  
//array안에 {} 넣을수도 있음 
  
const random = [...'hello',{...dog}]
                                
 ["h", "e", "l", "l", "o", {}]
0: "h"
1: "e"
2: "l"
3: "l"
4: "o"
5: {legs: 4, furry: true, isPet: true, adorable: true}

//이렇게 출력 됨! 

Rest (three dots but behave differently)

  • collecting down into a single array
function sum(...nums) {
    return nums.reduce((total,currentVal) => {
return total+currentVal;})}

sum(2,3,4)// 이렇게 해서 출력하면 9가 나옴 

//여기서 arrow function을 쓴다면
const numNum = (...nums) => (nums.reduce((total,currentVal) => total*currentVal))
  • unclaimed argument를 묶기도 함
function fullName(first, last, ...titles) {
  console.log('first',first)
  console.log('last',last)
  console.log('titles',titles)
}

fullName('joanne','kim','Yolo','FOMO','HAHHA');
/*first joanne
  last kim
  titles ["Yolo", "FOMO", "HAHHA"]
이렇게 출력 됨 
*/ 

Destructuring Array

variable 이름을 array에 입력한후 값을 찾을수 있음

const scores = ['joanne','Anne','mimi','rachel']
const [winner,second] = scores;
// winner 출력하면 'joanne', second 출력하면 'Anne'됨 
const [win,,third] = scores;
//third 출력하면 win과 콤마를 지나 'mimi'가 출력됨 
const [meme,...others] =scores;
//하면 others에 joanne을 제외한 나머지 3명이 출력 됨

Destructuring Object

variable name은 key name 과 동일하게 셋팅 해야함
혹은 key와 동일한 값을 지정해줘서 variable 값을 줄수 있음

const thirdBridge  = {
    TL : "Rachel",
    SA : "Clara",
    OC :  "Alan"}

const {TL,...OTHERS} = thirdBridge;
//OTHERS를 출력하면 
{SA: "Clara", OC: "Alan"}//나옴 
------------------------------------
const {TL : TeamLeader} = thirdBridge;
//TeamLeader출력하면 Rachel 이 나옴 

Nested Destructing

const results =[{
  first : 'joanne'
  last : 'kim'
  country: 'Korea'
},
{	first : 'Su'
 	last : 'Ong'
 	country: 'Singapore'
}] 
 const [,{country}] = results
 //하면 두번째 object 의 country 인 Singapore이 출력 됨 
  const [{first : jojo},{country}] = results
 //jojo하면 joanne이 출력됨 
 //더 깔끔한 코딩을위해선 아래와 같이 출력하는것도 좋음 
  
const [,silverMedal] = results;
const {country} = silverMedal;

Object

Shorthand Object

const getStats = (arr) => {
  const max= Math.max(...arr);
  const min= Math.min(...arr);
  const sum= arr.reduce((a,b)=> a+b);
  const avg= sum/arr.length;
  return { max,min,sum,avg};
  
  const reviews =[4,5,3,5,6,4,3,3,5,3];
  const stats = getStats(reviews);
  stats;
  //이렇게 하면 결과가 출력됨. 
  

Computed Properties

const role = 'host'
const person = 'seul'
const role2 = 'director'
const person2 = 'jojo' 

const team = {
  [role]=person
  [role2]=person2,
}
  //team 출력하면  { host : 'seul', director : 'jojo'} 나옴 
  
const addProp = (obj,k,v) => {
  return {
    ...obj,[k]:v }}

//이렇게도 할수 있음 
const addProp = (obj,k,v) => ({...obj,[k]:v })

const res = addProp(team,'happy',':)')
//{host: "seul", director: "jojo", happy: ":)"}이렇게 출력됨 

Adding Methods to Objects

const math = {
  numbers: [1,2,3,4,5],
  add: function(x,y) {
    return x+y;},
  multiply: function(x,y) {
    return x*y;}}

math.add(2,3) //하면 5가 출력되고 
math.multiply(2,3) //하면 6이 출력됨

Shorthand Syntax

const auth = {
  username : "TommyBot",
  login(){
    console.log('you are logged in')},
  logout(){
    console.log('you are logged out ')}
}

This

-아무것도 없이 This를정의하면 window가 뜬다
-function 안에 있으면 global scope이라 window를 부르지만, 막상 variable안에 object 안에서 있으면 this를 부를수 없음!

for example

console.log ("Hi")
console.log(this);
} //이렇게 하면 this 는 window를 가리킨다 하지만!! 

const person = {
  first : "jojo",
  second : 'lalayay',
  fullName() {
    console.log(this);}
  } // 이렇게 한뒤 person을 불러오면 object itself가 나온다 window가 아니라 this 가 들어있는 person object 전체를 보여줌 

const person = {
    first: 'joanne',
    last: 'kim',
    nickName: 'cher',
    fullName() {
        const {
            first,
            last,
            nickName} =this;
           return `${first} ${last} AKA ${nickName}`;
        },
        printBio() {
            this.fullName()
        }
        }// 이렇게 한 뒤에 person.fullName();을 출력하면 "joanne kim AKA cher"

This in methods

  • use the keyword this to access other properties on the same object
const person = {
    first: 'joanne',
    last: 'kim',
    nickName: 'cher',
    fullName() {
      return `${this.first} ${this.last}`
    }
}
person.fullName(); //joanne kim
person.last ="park"
person.fullName(); //joanne park
const annoyer = {
phrases : ["like", "omg" ],
 pickPhrase() {
   const {phrases} = this;
   Math.floor(Math.random()*phrase.length);
   return phrases[idx]
 },
  start() {
    setInteral(function  () {
      console.log("ididididi"),3000)
    }
      
  }  
}
profile
코린이 프론트엔드 개발자💻💛🤙🏼

0개의 댓글