polyfill을 생성하여 array.reduce 이해하기
array.reduce
입니다. 따라서 이 기사에서는 polyfill을 만드는 동안 reduce 함수에 대해 알아봅니다.좋아, 처음부터 시작하자.
reduce
함수는 콜백 함수를 사용합니다. 따라서 우리가 사용하는 방법은 다음과 같습니다.let arr = [1, 2, 3, 4, 5]
arr.reduce(function(){
console.log("hello")
})
이제 이것을 실행하면 볼 수 있습니다.
polyfill
hello는 콘솔에 4번 인쇄되었습니다. 그러나 배열에는 5개의 요소가 있습니다. 따라서 reduce 함수는
array.length - 1
번 호출됩니다. 따라서 간단한 for 루프를 사용하여 이 동작을 쉽게 모방할 수 있습니다.function myReduce(arr, cb){
for(let i = 0; i < arr.length - 1; i++){
cb()
}
}
let arr = [1, 2, 3, 4, 5]
myReduce(arr, function(){
console.log("hello")
})
이 코드를 실행하면 출력이 동일하다는 것을 알 수 있습니다. 그러나 이것은 그다지 유용하지 않습니다. 계속 진행하겠습니다.
reduce
함수가 콜백 함수를 호출할 때 일부 인수도 전달합니다. console.log
수신하는 처음 두 인수를 허용합니다.let arr = [1, 2, 3, 4, 5]
arr.reduce(function(a, b){
console.log(a, b)
})
출력이 정말 이상하게 보입니다. 처음에 a의 값은 배열의 첫 번째 요소였고 b의 값은 배열의 두 번째 요소였습니다. 그 후 다음 함수 호출에서 a의 값은
undefined
이고 b의 값은 배열의 다음 요소였습니다. 무슨 일이야? 콜백 함수에서 무언가를 반환해 봅시다.let arr = [1, 2, 3, 4, 5]
arr.reduce(function(a, b){
console.log(a, b)
return "hello"
})
처음에는 a의 값이 배열의 첫 번째 요소인 것처럼 보입니다. 콜백 함수에서 반환하는 값은 a의 값이 됩니다. 커스텀 함수에서 그렇게 해봅시다.
function myReduce(arr, cb){
let a = arr[0]
for(let i = 0; i < arr.length - 1; i++){
//setting the value of a to what ever the call back returns
a = cb(a, arr[i])
}
}
let arr = [1, 2, 3, 4, 5]
myReduce(arr, function(a, b){
console.log(a, b)
return "hello"
})
우리의 출력이 조금 다른 것 같습니다. 이를 수정하려면
for(let i = 0; i < arr.length - 1; i++)
라고 말하는 대신 for(let i = 1; i < arr.length; i++)
라고 말할 수 있습니다.function myReduce(arr, cb){
let a = arr[0]
for(let i = 1; i < arr.length; i++){
//setting the value of a to what ever the call back returns
a = cb(a, arr[i])
}
}
let arr = [1, 2, 3, 4, 5]
myReduce([1, 2, 3, 4, 5], function(a, b){
console.log(a, b)
return "hello"
})
그리고 이제 우리의 출력은 동일합니다.
reduce
함수는 두 번째 인수를 사용할 수도 있습니다. 두 번째 인수를 전달하면 어떻게 되는지 봅시다.let arr = [1, 2, 3, 4, 5]
arr.reduce(function(a, b){
console.log(a, b)
return "hello"
}, "Hi") //passing hi as second argument
따라서 우리가 두 번째 값을 out
reduce
함수에 전달하면 a의 초기 값이 우리가 전달한 값이 되고 콜백 함수에서 반환되는 값이 되는 것처럼 보입니다. 그리고 b의 값은 배열의 첫 번째 요소에서 시작합니다. 그렇다면 이 논리를 사용자 지정 JS 함수에도 추가해 보겠습니다.function myReduce(arr, cb, initialVal){
let a = arr[0]
let startIdx = 1
if(initialVal){
a = initialVal
startIdx = 0
}
for(let i = startIdx; i < arr.length; i++){
//setting the value of a to what ever the call back returns
a = cb(a, arr[i])
}
}
let arr = [1, 2, 3, 4, 5]
myReduce(arr, function(a, b){
console.log(a, b)
return "hello"
}, "Hi")
좋아, 우리는 진전을 이루고 있다. 이제 우리의 배열 축소 기능도 무언가를 반환합니다. 수 있습니다
console.log
.let arr = [1, 2, 3, 4, 5]
let res = arr.reduce(function(a, b){
console.log(a, b)
return "hello"
}, 0)
console.log("res: " + res)
그것은 또한 hello를 반환하는 것처럼 보입니다. 콜백 함수에서 새로운 것을 반환해 봅시다.
a + b
를 반환할 수 있습니다. 따라서 콜백 함수가 호출될 때마다 b의 값이 a에 추가됩니다.let arr = [1, 2, 3, 4, 5]
let res = arr.reduce(function(a, b){
console.log(a, b)
return a + b
}, 0)
console.log("res: " + res)
여기에서 a의 마지막 콜백 함수 호출 값이 10이고 b가 5인 것을 볼 수 있습니다. 따라서 콜백 함수가 반환됨
10 + 5
은 a의 최종 값이10 + 5
또는 15
그리고 reduce 함수도 15
를 반환합니다. 따라서 reduce 함수는 a의 최종 값을 반환합니다.이제 커스텀 함수도 그렇게 하도록 합시다.
function myReduce(arr, cb, initialVal){
let a = arr[0]
let startIdx = 1
if(initialVal){
a = initialVal
startIdx = 0
}
for(let i = startIdx; i < arr.length; i++){
//setting the value of a to what ever the call back returns
a = cb(a, arr[i])
}
return a //returning the final value of a
}
let arr = [1, 2, 3, 4, 5]
let res = myReduce(arr, function(a, b){
console.log(a, b)
return a + b
}, 0)
console.log("res: " + res)
거의 다 왔어. 이제
let res = myReduce(arr, ...)
라고 말하는 대신 arr.myReduce
라고 말할 수 있습니다. 그렇게 하려면 myReduce
의 프로토타입에 array
를 추가해야 합니다.Array.prototype.myReduce = function(cb, initialVal){
let arr = this //'this' is the array on which this function was called
let a = arr[0]
let startIdx = 1
if(initialVal){
a = initialVal
startIdx = 0
}
for(let i = startIdx; i < arr.length; i++){
//setting the value of a to what ever the call back returns
a = cb(a, arr[i])
}
return a //returning the final value of a
}
let arr = [1, 2, 3, 4, 5]
let res = arr.myReduce(function(a, b){
console.log(a, b)
return a + b
}, 0)
console.log("res: " + res)
그리고 당신은 간다. 이제
reduce
함수가 어떻게 작동하는지 알았을 뿐만 아니라 처음부터 자신만의 reduce 함수를 만들었습니다. 이제 기술을 연마하기 위해 확인할 수 있습니다.그리고 이러한 예
배열의 합 구하기
let arr = [1, 2, 3, 4, 5]
let sum = arr.reduce(function(a, b){
return a + b
})
//or using arrow function
let sum = arr.reduce((a, b) => a + b)
console.log(sum) //output: 15
let arr = [1, 2, 2, 3, 4, 4, 5]
let newArr = arr.reduce((a, b) => {
if(a.indexOf(b) == -1) a.push(b)
return a
}, [])
console.log(newArr) //output: [1, 2, 3, 4, 5]
let arr = [2, 5, 345, 32, 52]
let max = arr.reduce((a, b) => {
if(b > a) a = b
return a
})
console.log(max) //output: 345
지금은 여기까지입니다. 내 다른 기사를 확인하십시오.
.ltag__user__id__728097 .follow-action-button {
배경색: #000000 !중요;
색상: #ffffff !중요;
테두리 색상: #000000 !중요;
}
this link
따르다
Shuvo
Reference
이 문제에 관하여(polyfill을 생성하여 array.reduce 이해하기), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/0shuvo0/understanding-arrayreduce-by-creating-its-polyfill-4c23텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)