The Web Developer (Udemy) - Javascript (3)

‍정진철·2022년 7월 19일
0

web devloper (udemy)

목록 보기
7/34

1. 콜백과 배열

G O A L S

  • Use the new arrow function syntax.

  • Understand and use there methods:
    -> forEach
    -> map
    -> filter
    -> find
    -> reduce
    -> some
    -> every


    1) For each

    Accepts a callback function.
    Calls the function once per element in the array

 const numbers= [1,2,3,4,5,6,7,8,9,10];
 

numbers.forEach(function(el) {
    console.log(el)
})

const movies = [
    {
        title: 'Amadeus',
        score: 99
    },
    {
        title: 'Stand By Me',
        score: 85
    },
    {
        title: 'Parasite',
        score: 95
    },
    {
        title: 'Alien',
        score: 90
    }

]

//fucntion 의 매개변수는 배열안에 존재하는 각각의 하나의 원소들을 의미.
movies.forEach(function(movie) {
    console.log(`${movie.title} - ${movie.score} /100}`)
})

2) Map

Creates a new array with the results of calling a callback on every element in the arry.

const numbers= [1,2,3,4,5,6,7,8,9,10];

const doubles = numbers.map(function(num){
    return num *2;
})  


const movies = [
    {
        title: 'Amadeus',
        score: 99
    },
    {
        title: 'Stand By Me',
        score: 85
    },
    {
        title: 'Parasite',
        score: 95
    },
    {
        title: 'Alien',
        score: 90
    }

]

//fucntion 의 매개변수는 배열의 각각의 
const titles = movies.map(function(movie){
    return movie.title.toUpperCase();
})

3) 화살표 함수

  • function 키워드 없이 함수 생성 가능.
const add = (x,y) => {
    return x+y
}

const square = (x) => {
    return x*x;
}
  • 괄호 안 변수는 매게변수.

4) 화살표 함수의 반환

암시적 반환

const rollDie = () => (
    Math.floor(Math.random() * 6) + 1
)

// 중괄호는 소괄호로 변경.
// return 값이 없더라도 반환

const add = (a,b) => (a+b) //한 줄

단계별 함수


const isEven = function(num) {
    return num % 2 === 0;
}

const isEvan = (num) => {
    return num % 2 === 0;
}

const isEvan = num => {
    return num % 2 === 0;
}

const isEvan = num => (
    num % 2 === 0
);

const isEvan = num => num % 2 === 0; (최종)
  • 괄호 안에는 단 '하나'의 표현식만 존재해야함.

5) setTimeout 과 setInterval

setTimeout

setTimeout(() => {
    console.log("HELLO")
}, 3000)

setInterval

const id = setInterval(() => {
    console.log(Math.random());
}, 2000);
//2초마다 출력


중단하고 싶으면 
clearInterval(id);

6) filter 메소드

FILTER

  • creates a new array with all elements that pass the test implemented by the provided function.
const numbers = [1,2,3,4,5,6,7,8,9,10];

numbers.filter(n => {
    return n < 10
})

const movies = [
    {
        title: 'Amadeus',
        score: 99,
        year: 1984
    },
    {
        title: 'Stand By Me',
        score: 85,
        year: 2013
    },
    {
        title: 'Parasite',
        score: 95,
        year: 2004
    },
    {
        title: 'Alien',
        score: 90
    }
]

const goodMovies = movies.filter(movie => {
    return movie.score > 85
})
//동일 코드
==> const goodMovies = movies.filter(m => m.score > 85)
==> const badMovies = movies.filter(m => m.score < 60)
==> const recentMovies = movies.filter(m => m.year > 2006)

map , filter 메소드 혼용

const goodMoivesTitles = movies
	.filter(m => m.scroe >80)
	.map(m => m.title);

Filter Exercise

function validUserNames(usernames) {
 let filterdUserNames = usernames.filter(function(username){
      return username.length < 10;
      })
      return filterdUserNames;
}

7) Some 과 every 메소드

SOME

  • similar to every, but returns true if ANY of the array elements pass the test function.
const exams = [90, 87, 94, 77, 83, 92, 78, 81,99];

exams.every(score => score > 80) //false
exams.every(score => score > 70) //true

exams.some(score => score > 95) //true
  • every는 해당 조건을 '모두' 만족해야 true.
  • some은 해당 조건을 '하나'라도 만족하면 true.

Some/Every Exercise

function allEvens(elements) {
    if (elements.every(element => element % 2 ===0)) {
        return true
    } else {
        return false;
    }
}


8) reduce 메소드

Excutes a reducer function on each element of the array, resulting in a single value.

  • 연산을 통해 하나의 값만 도출. (연산방법은 정의하기 나름)


const prices = [9.99, 1.50, 19.99, 49.99, 30.50]

prices.reduce(total, element) => {
    return total + element
})

// prices.reduce((total, element) => total + price)

//콜백을 위한 두 매개변수

const prices = [9.99, 1.50, 19.99, 49.99, 30.50]

const minPrice = prices.reduce((min , element) => {
    if (element < min) {
        return element
    } else {
        return min
    }
})


const movies = [
    {
        title: 'Amadeus',
        score: 99,
        year: 1984
    },
    {
        title: 'Stand By Me',
        score: 85,
        year: 2013
    },
    {
        title: 'Parasite',
        score: 95,
        year: 2004
    },
    {
        title: 'Alien',
        score: 90,
        year : 1999
    }
]

const highestRated = movies.reduce(bestMovie, curMovie) => {
    if (bestMovie.score < curMovie.score) {
        return curMovie;
    } else{
        return bestMovie;
    }
})

초기값 설정도 가능

const evens = [2,4,,6,8]

evens.reduce((sum, num) => sum + num, 100) //120

9) 화살표 함수와 'this'

const person = {
    fistName: 'Viggo',
    lastName: 'Mortensen',
    fullName: () => {
        return `${this.firstName} ${this.lastName}`
    }
}

  • 화살표 함수 안에 있는 this 키워드는 함수가 만든 범위를 가르킴.
  • 즉, this 키워드가 'Window' 객체를 가르키는중.

2) JS의 최신 기술들

1) 기본 매개 변수

  function rollDie(numSides = 6) {
    return Math.floor(Math.random() * numSides) + 1
  }

function greet(person, msg = "Hey there", punc='!') {
   return `${msg} , ${person}${punc}`
}
  • 디폴트값을 주고싶다면 뒤에다 배치. 앞에는 디폴트 없는 파라메터 배치.

2) 함수 호출시의 스프레드 구문

const nums = [13, 423, 55, 25, 3, 4,58, 1000]

console.log(nums);
console.log(...nums);


3) 행렬 리터럴 스프레드 구문


4) 객체 스프레드 구문


const dataFromForm = {
    email: 'blueman@gmail.com',
    password: 'tobias123!',
    username: 'tfunke'
}

const newUser = {...dataFromForm, id:2345, isAdmin:false}


5) Rest 매개 변수

function sum(...nums) {
    console.log(nums)
}


function sum(...nums) {
    return nums.reduce((total, el) => total + el);
}


function raceResults(gold, silver, ...everyoneElse ) {
    console.log(`GOLD MEDAL GOES TO: ${gold}`)
    console.log(`SILVER MEDAL GOES TO: ${silver}`)
    console.log(`AND THANKS TO EVERYONE ELSE: ${everyoneElse}`)

}


6) 배열 분해

DESTRUCTURING

  • A short, clean syntax to 'unpack':
    -> values from arrays
    -> Properties from objects
    into distinct variables.

    		 const raceResults = ['Ann', 'Bob', 'Clony', 'John', 	'Tina', 'Andy']
    
    		const [gold, silver, bronze, ...everyoneElse] = 		raceResults;
    


7) 객체 분해

const user = {
    email: 'heavy@gmail.com',
    password: 'tkfkdgo@@!!234',
    firstName: 'Harvey',
    lastName: 'Milk',
    born:1999,
    died:2222,
    bio: 'Harvey Bernard Milk was an America politician and the first openly',
    city : 'San Francisco',
    state: 'California'
}

const {email, firstName, lastName, city} = user;


const {born: bonrYear, died: deathYear} = user;

디폴트 값 지정


const user2 = {
    email: 'Stacy@gmail.com',
    firstName: 'Stacy',
    lastName: 'Gonzalez',
    born: 1987,
    city: 'Tulsa',
    state: 'Oklahoma'
}

const {city , state, died = 'N/A'} = user2;


8) 매개 변수 분해


const user = {
    email: 'heavy@gmail.com',
    password: 'tkfkdgo@@!!234',
    firstName: 'Harvey',
    lastName: 'Milk',
    born:1999,
    died:2222,
    bio: 'Harvey Bernard Milk was an America politician and the first openly',
    city : 'San Francisco',
    state: 'California'
}

function fullName({firstName, lastName}) {
    return `${firstName} ${lastName}`
}


const movies = [
    {
        title: 'Amadeus',
        score: 99,
        year: 1984
    },
    {
        title: 'Sharknado',
        score: 35,
        year: 2013
    },
    {
        title: '13 Going On 30',
        score: 70,
        year: 2004
    },
    {
        title: 'Stand By Me',
        score: 85,
        year: 1986
    },
    {
        title: 'Waterworld',
        score: 62,
        year: 1995
    },
    {
        title: 'Jingle All The Way',
        score: 71,
        year: 1996
    },
    {
        title: 'Parasite',
        score: 95,
        year: 2019
    },
    {
        title: 'Notting Hill',
        score: 77,
        year: 1999
    },
    {
        title: 'Alien',
        score: 90,
        year: 1979
    }
]
    
movies.filter(({score}) => score >= 90)

movies.map(movie => {
    return `${movie.title} (${movie.year}) is rated ${movie.score}`
})

(매개변수 분해)
-> movies.map(({title,year,score}) => {
    return `${title} ${year} is rated ${score}`
})

profile
WILL is ALL

0개의 댓글