javascript
javascript의 선택적 인수 위험
웹 개발자 승민
2020. 7. 30. 18:50
http://www.wirfs-brock.com/allen/posts/166
A JavaScript Optional Argument Hazard
A JavaScript Optional Argument Hazard on February 24, 2011 My recent post on testing for negative 0 in JavaScript created a lot of interest. So today, I’m going to talk about another bit of JavaScript obscurity that was also inspired by a Twitter threa
www.wirfs-brock.com
let test_arr = ['1', '2', '3']
let result_arr = test_arr.map(parseInt)
// 의도한 결과 : [1, 2, 3]
console.log(result_arr)
// 실제 결과 : [1, NaN, NaN]
우리는 문자열에 대해서 정수로 반환된 배열을 얻고 싶었다.
그런데 왜 의도한 것과 다른 결과가 나오는 것일까?
이는 map과 parseInt에 대한 제대로 된 이해를 하지 못했기 때문에 일어난 문제이다.
callback(element, index, thisArray)
Array.map(callback)
먼저 map 메소드와 callback 함수의 구문은 이렇다.
parseInt(string, radix)
그리고 parseInt 메소드의 구문은 이렇다.
즉 우리는 map에 대하여
parseInt('1')
parseInt('2')
parseInt('3')
와 같은 결과를 얻고 싶었지만 실제로 동작되는 것은
parseInt('1', 0) // 1
parseInt('2', 1) // 1진수에 대해서 2?? => NaN
parseInt('3', 2) // 2진수에 대해서 3?? => NaN
위와 같은 결과이다.
그렇기 떄문에 의도와 다른 결과가 생겼던 것이다.