JavaScript - The pit of map and parseInt

question:

var arrs = [‘1,2,3’]; 
var r = arrs.map(parseInt); 
alert(r);//1,NaN,NaN

map

 arr.map(function callback(currentValue[, index[, array]]) {
    // Return element for new_array
}[, thisArg])

parseInt

parseInt(string, radix);

Because map() takes three parameters and parseInt() takes two parameters, the third parameter of map is ignored by parseInt.
Now let's analyze the program. If the first element of arr is executed now, that is, '1'; corresponding to the map parameter, we can see that the first parameter passed into the map is the passed element '1'; the second The parameter is its index 0;
these two parameters are passed into parseInt, that is, parseInt('1', 0); corresponding to the above parameter rules of parsent, the result is 1;
similarly, parseInt('2' ,1) //radix is ​​less than 2 and returns NaN
parseInt('3',2) //3 is an illegal binary number, returns NaN

solve:

function  parseInt_base10(s)
{
    return parseInt(s,10);
}

r = arrs.map(parseInt_base10,arrs);
//或者r = arrs.map(parseInt_base10);
alert(r);//[1,2,3]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325033300&siteId=291194637