728x90

 

Array.prototype.map() & map(Number)

var a = "1, 2, 3, 4, 5";

console.log(typeof(strToNum)); // 'string'

var b = a.split(',').map(function(item) {
    return Number(item);
    //return parseInt(item,10); -> 10진수로 변환
});

console.log(b); //[1, 2, 3, 4, 5]

for(x of bb){
	console.log(typeof(x));
}
//결과 : Number

 

문자열을 숫자형으로 변환하기 위해서는 위처럼 간단한 작업이지만 코드가 길어지게 됩니다. 

 

이때 유용하게 사용할 수 있는 코드가 있습니다.

 

✅ map(Number) 입니다.

 

var a = "1, 2, 3, 4, 5";

console.log(typeof(strToNum)); // 'string'

var b = a.split(',').map(Number);

for(x of bb){
	console.log(typeof(x));
}
//결과 : Number

 

map(Number)만 사용하면 간편하게 숫자형으로 변환할 수 있습니다.

 

 

 

참고 ❗

 

[JavaScript] Array filter() 사용법과 map()과 차이점

filter() "배열".filter(callBackFunction(currValue, index, array), newValue); filter()는 말 그대로 걸러주는 역할을 하는 함수입니다. 주로 특정 조건을 만족하는 새로운 배열을 필요로 할 때 사용하는 편입니다. ca

pixx.tistory.com