Reputation: 3
`
function string2int(s) {
var arr = [];
for (let x of s) {
arr.push(x);
}
arr.map(function (x) {return x*1;});
var result = arr.reduce(function (x, y) {return x*10 + y;});
alert(result);
}
string2int('123456');
`
`
function string2int(s) {
var arr = [];
for (let x of s) {
arr.push(x*1);
}
var result = arr.reduce(function (x, y) {return x*10 + y;});
alert(result);
}
string2int('123456');
`
As shown by the name of the function name string2int, the purpose of both two pieces of code is to transform string '123456' into int 123456, the idea is to trasform '123456' into arr(['1', '2', '3', '4', '5', '6']) firstly, then use each char to multiply 1 to turn elements in the array arr into int, and finally use reduce function to get the expected int 1234156. However, it turned out that only the second piece of code worked properly, the first piece would output the result 10203040506.
I added alert(arr); under arr.map(function (x) {return x*1;}); in the first piece of code and found that even after the execution of map function, elements in array arr were still int type, why is this? Besides, in that case, how was the final result 10203040506 got?
Upvotes: 0
Views: 51
Reputation: 36
The problem with the first part is that you are using the map method, which returns a new array and will never change the original arr array. By doing so, your items inside arr will still be of type 'string', and also the variable result. You can verify this by adding this to the last line of the first function:
console.log(typeof result);
In order for your code to work, you will need to declare a new variable for the map method to return, and then work the reduce method on it. Example:
let newArr = arr.map(function (x) {return x*2;});
var result = newArr.reduce(function (x, y) {return x*10 + y;});
Edit: Alternatively you could use the forEach method instead of map, and the original array arr would be changed.
Upvotes: 1
Reputation: 62686
The first function fails to convert digits (strings that represent numerals) into into ints. The least invasive fix is to do that conversion as the digits are pushed to arr
with a unary +
...
function string2int(s) {
var arr = [];
for (let x of s) {
arr.push(+x); // convert to int here
}
// arr.map(function (x) {return x*1;}); // this does nothing
var result = arr.reduce(function (x, y) {return x*10 + y;});
alert(result);
}
string2int('123456');
It can be improved by realizing that split('')
does the work of the first loop, and that conversion to ints from digits can happen in the reduce...
function string2int(s) {
return s.split('').reduce((a, digit) => a*10 + +digit, 0)
}
alert(string2int('123456'));
Upvotes: 0