화살표 함수로 맥스, 섬 만들어보기
const arr = [1,2,3,4,5];
const max = arr.reduce((a,b)=>(a>b?a:b));
console.log(max);
const sum = arr.reduce((x,y)=>{return x+y});
console.log(sum);
객체에서 필터. 포이치 해보기
const a = [{
id:5,
name : '바보',
year:6,
result:4.1,
}
,{
id:7,
name:'haha',
year:12,
result: 51
}
]
a.filter(a=>a.id>5).forEach(a=>console.log(a));
a.filter(a=>a.id>5).forEach(console.log);
// 왜 이런 결과가 나오는가?
// JavaScript에서 Array.prototype.forEach 메서드와 console.log 메서드 모두 여러 개의 인자를 받을 수 있지만, 이들이 인자를 처리하는 방식은 매우 다릅니다.
//
// forEach(callbackfn)은 첫 번째 인자로 콜백 함수를 받아 배열의 각 요소에 대해 해당 함수를 실행합니다. 이 콜백 함수는 다음 세 가지 인자를 받을 수 있습니다: 현재 요소값, 현재 인덱스, 원본 배열입니다.
//
// console.log([data][, ...])는 인자를 하나 이상 받을 수 있으며, 각 인자를 공백으로 구분하여 로그에 출력합니다.
//
// 그러므로, a.filter(a=>a.id>5).forEach(a=>console.log(a)) 코드는 filter로 걸러진 배열의 각 요소를 console.log로 출력하는 것을 의미합니다.
//
// 반면, a.filter(a=>a.id>5).forEach(console.log) 코드는 console.log를 forEach의 콜백 함수로 사용합니다. 따라서 console.log는 forEach에서 제공하는 세 가지 인자(현재 요소값, 현재 인덱스, 원본 배열)를 모두 받게 됩니다. 그 결과로, 로그에는 현재 요소값, 인덱스, 그리고 전체 배열이 함께 출력됩니다.
//
// 따라서 이 두 코드는 같은 행동을 하는 것 처럼 보이지만 실제로는 다른 결과를 보여줍니다.
// 포리치에는 로그에는 현재 요소값, 인덱스, 그리고 전체 배열이 함께 출력되는 것을 알 수 있다.
화살표함수 만드는방법. 그리고 그 함수들은 prototype이 있는가?
function add1(a,b){
return a+b;
}
const add2 = (a,b)=>{
return a+b
}
function fnc1(){
}
const fn2 = ()=>{
}
console.log(add1.hasOwnProperty('prototype'));
console.log(add2.hasOwnProperty('prototype'));
console.log(fnc1.hasOwnProperty('prototype'));
console.log(fn2.hasOwnProperty('prototype'));
console.log(add1(10,20));
console.log(add2(10,20));
//화살표 함수의 정의
const add = (a,b) => {
console.log(a+b);
}
//중괄호대신 소괄호를 쓰면 결과가 리턴됨
const sub = (a,b)=>(
a-b
);
const mul = ()=>{
return 10*20;
}
// 매개변수가 하나인 화살표 함수에서는 매개변수 부분에 소괄호를 생략 가능
const div = a=>{
console.log(100/a);
}
add(10,20);
const subRes = sub(20,10);
console.log(subRes);
const mulRes = mul();
console.log(mulRes);
div(5);
댓글 영역