Exercise: Don’t use JavaScript’s built-in parseInt() to implement a string2int() function with map() and reduce() operations:
I have some problem about those solution! it only return “NaN” in the final results;
understand how it works, but return NaN
function string2int(s) {
let arr=s.split("");
arr=arr.map(function(x){
return x*1;
});
arr=arr.reduce(function(x,y){
return x*10+y
});
return arr;
}
// NaN
return NaN, and I don’t know why…
2. I don’t understand +el, and it get NaN
function string2int(s) {
var arr= s.split("").map(function(el){return+el;});
return arr.reduce(function(x,y){
return x*10 + y;
});
}
//NaN
3.The executable code
function string2int(s){
//利用reduce
var arr = new Array();
var len = s.length;
for(var i = 0; i < len; i++){
arr.push(s.charCodeAt(i)-48); // '0' 的ASCII为48
}
var res = arr.reduce(function(x,y){
return x*10+y;
});
return res;
console.log(res+"with type of "+typeof res);
}