728x90

✨기존 function에 this(or null)와 arguments(array or an array-like object)를 넣어 함께 불러낼 수 있는 helper method

(e.g., Math.max.apply(null, array)) 왼쪽처럼 Math.max에 apply(null, array)를 적용해주면 array안에 있는 수 중에
가장 큰 수를 손쉽게 구할 수 있다.
재귀(Recursive)함수에서 Dynamic Programming(Memoize)을 사용할 때도 적용할 수 있다.

 

💻Example Code

const arr = [1, 2, 3, 4, 5, 6, 7];
const max = Math.max.apply(null, arr);

console.log(max);

실행 결과(1~7 중에 가장 큰 수는 7)

😋 평소에 자주 쓸 일은 없었지만, Algorithm을 공부하면서 종종 사용하게 되었다.
max를 구하기 위한 classic 방식은 모두 이해하고 알고 있으니, 앞으로 간략한 Math.max.apply()를 주로 이용해보자.
단, 첫 번째 this(or null)의 사용법은 조금 더 익힐 필요가 있겠다.

👉 자세한 내용은 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

'JavaScript > Built-in Method etc.' 카테고리의 다른 글

Array.prototype.slice()  (0) 2019.12.23
Math.floor()  (0) 2019.12.23
Number.prototype.toFixed()  (0) 2019.12.22
String.prototype.split()  (0) 2019.12.22
String.prototype.trim()  (0) 2019.12.22

+ Recent posts