Convert String to Array and then to Numbers;

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;

  1. 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);
}

What are you testing this with? All three of your solutions work for me.

playcode.io and http://pythontutor.com/javascript.html#mode=edit

I was trying to ask what sting you were testing with. Neither of those links link to the code we’re discussing.

I can test and pass all three of your functions:

function string2int1(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;
}
const test1 = string2int1('123');
console.log('test1', typeof test1, test1);
// test1 number 123

function string2int2(s) {
  var arr = s.split('').map(function(el) {
    return +el;
  });
  return arr.reduce(function(x, y) {
    return x * 10 + y;
  });
}
const test2 = string2int2('456');
console.log('test2', typeof test2, test2);
// test2 number 456

function string2int3(s) {
  var arr = new Array();
  var len = s.length;
  for (var i = 0; i < len; i++) {
    arr.push(s.charCodeAt(i) - 48);
  }
  var res = arr.reduce(function(x, y) {
    return x * 10 + y;
  });
  return res;
}
const test3 = string2int3('789');
console.log('test3', typeof test3, test3);
// test3 number 789

There is a working pen here.

1 Like

I haven’t figure out why there it’s like that, but it works now! thank u so much!