개발하는 일상

javascript parseInt가 이상하다면? 본문

개발 간단 팁

javascript parseInt가 이상하다면?

롯데빙빙바 2021. 10. 24. 22:33

아래 코드의 결과를 예측해보세요.

const foo = '12,4,15,163,51'.split(',');
const bar = foo.map(parseInt);
console.log(bar);

아래 코드와는 결과가 다를까요?

const foo = '12,4,15,163,51'.split(',');
const bar = foo.map((num)=>parseInt(num));
console.log(bar);

첫 번째 코드의 결과는

[ 12, NaN, 1, 1, NaN ]

두 번째 코드의 결과는

[ 12, 4, 15, 163, 51 ]

입니다.

이유는 mapparseInt가 어떻게 정의되어 있는지를 보면 알 수 있습니다.

// map
map<U>(callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): U[];

// parseInt
declare function parseInt(string: string, radix?: number): number;

타입스크립트의 정의라 알아보기 힘드실 수 있지만, 필요한 것만 알아보면 됩니다. map메소드를 보시면, 첫 번째 매개변수인 callbackfn에 인자가 3개가 전달됩니다. parseInt에는 매개변수 2개가 선언되어 있습니다. 즉, 맨 처음 보여드렸던 코드는 사실 아래와 같습니다.

const foo = '12,4,15,163,51'.split(',');
const bar = foo.map((num, index)=>parseInt(num, index));
console.log(bar);

parseInt에 전달되는 두 번째 인자는 첫 번째 인자를 몇 진수로 해석할지에 대한 숫자입니다(더 자세한 설명은 mdn문서 https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/parseInt 를 참고해주세요).
따라서 원래 의도와 다른 결과가 나오게 됩니다.

Comments