Purpose:
不使用JavaScript内置的parseInt()函数,利用map和reduce操作实现一个string2int()函数:
Instead of using the parseInt() function built in JavaScript, a string2int() function is implemented by using map and reduce operations.
Code:
function string2int(s) {
return s.split('').map(function(data) { return +data }).reduce(function(x, y) {
return x * 10 + y;
});
}
// test
if (string2int('0') === 0 && string2int('15244') === 15244 && string2int('10210') === 10210) {
if (string2int.toString().indexOf('parseInt') !== -1) {
console.log('Do not use parseInt()!');
} else if (string2int.toString().indexOf('Number') !== -1) {
console.log('Do not use Number()!');
} else {
console.log('The test was successful');
}
}