728x90

✨ 소수점을 표시하기 위한 helper method

(e.g., 숫자변수.toFixed(2)) 왼쪽처럼 숫자값이 들어있는 변수에 toFixed(2)를 이용해주면 소수점 아래 2번째 값까지 표시가 가능하다.
기본적으로 JavaScript의 숫자는 Number로 통합되어 관리되고 표시되지만, int가 아니며 floating  point 속성을 가지고 있다.
(값의 통일성을 위해 의도적으로 소수점을 맞추고 싶을 때 유용할 것 같다. default는 반올림(round)이다)

 

💻Example Code

const num = 10.567

console.log(num.toFixed(2));

실행 결과 (10.567의 소수점 아래 2번째에서 반올림되어 1.57 출력)

😋 아직 어딘가에서 사용해보지는 않았지만, 백준 Algorithm을 풀면서 출력 형식을 똑같이 맞춰줘야하나?
생각하며 검색하다가 찾은 helper method이다. 언젠가는 분명 사용할 일이 있을 것 같다.

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

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

Array.prototype.slice()  (0) 2019.12.23
Math.floor()  (0) 2019.12.23
Function.prototype.apply()  (0) 2019.12.22
String.prototype.split()  (0) 2019.12.22
String.prototype.trim()  (0) 2019.12.22
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
728x90

✨ '단순 문자열'을 '배열 문자열'로 변환하기 위해 꼭 필요한 helper method이다.

(e.g., 'Hello World') 왼쪽의 string이 있을 때, split(' ')을 사용해주면 ' '(space)기준으로 문자열을 나누어 새로운 배열이 생성된다. (기본적으로 split('separator') 형식으로 사용하며, ' '(space), '\n'(Line Feed) 등 여러가지 separator를 넣어 사용한다)

 

💻Example Code

const str = 'Hello World';

console.log(str);
console.log(str.split(' '));

실행 결과(위 str, 아래 str.split(' '))

위 'Hello World'는 단순 str의 출력이며, 아래 배열(array)은 str.split(' ')의 출력 결과다.

😋 split() helper method은 정말 많은 곳에서 쓰인다.
최근 백준 algorithm을 풀 때, 입력값의 마지막에 \n가 붙어있었다.
split('\n')을 통해 배열로 전환되면서 마지막 index에 '' 공백 배열 문자열이 하나 더 추가되었고, 이것이 답을 도출하는데 오류를 발생시켰다. 
만약 \n(Line Feed)을 이용해 문자열을 분리해야 할 때가 온다면, trim()을 이용하여 마지막 \n 제거를 한 후 split('\n')할 것을 추천한다.

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

'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
Function.prototype.apply()  (0) 2019.12.22
String.prototype.trim()  (0) 2019.12.22
728x90

✨white space를 제거하여, 정확한 string값을 제어하기 위해 꼭 필요한 helper method이다.

(e.g., '   Hello World   ') 왼쪽의 string이 있을 때, trim을 사용해주면 문자열 기준 '앞', '뒤'의 white space를 없애준다.
(white space는 characters(space, tab, no-break space, etc.) 와 terminator characters (LF, CR, etc.)이 해당된다)

 

💻Example Code

let str = '   Hello World   ';

console.log(str.trim()); // 'Hello World';

실행 결과(위와 아래의 공백이 다른 것을 볼 수 있다)

위는 console.log(str.trim()); 의 실행결과이며, 아래는 console.log(str);의 실행결과이다.

😋 trim() helper function은 백준에서 algorithm을 풀 때, 받아오는 입력값을 정리할 때 유용하게 사용하고 있다.

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

'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
Function.prototype.apply()  (0) 2019.12.22
String.prototype.split()  (0) 2019.12.22

+ Recent posts