728x90

✨ 소수점 이하를 버리기 위한 Math의 helper method

(e.g., Math.floor(arr.length/2)) arr.length === 5 라고 가정할 때, 2라는 값을 도출할 수 있다.
Pyramid and Merge Sort Algorithm 등 여러곳에서 유용하게 사용했다.
(주로 array의 중간(midpoint or center)지점을 찾을 때 사용해왔으며, 그 외에도 다양한 곳에서 자주 사용된다)

💻Example Code

const arr = [1, 2, 3, 4, 5];

console.log( Math.floor(arr/2) );

실행 결과(2.5에서 소수점 이하를 버리고 2 출력)

😋 array의 index는 기본적으로 0부터 시작하기 때문에 홀수 개수의 array가 있을 때 center를 찾기에 유용하다.
특히, Array.prototype.slice() 와 연계하여 사용할 때 편하다. slice(begin index, End index) 형식으로 array(0,2)처럼 array를 자른다면, 0부터 1까지 index의 값만 slice 되기 때문이다.

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

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

Math.sign()  (0) 2019.12.24
Array.prototype.slice()  (0) 2019.12.23
Number.prototype.toFixed()  (0) 2019.12.22
Function.prototype.apply()  (0) 2019.12.22
String.prototype.split()  (0) 2019.12.22

+ Recent posts