最近在刷廖雪峰的JavaScript教程,受益匪浅…特此记录,NoScript加油每一天!
练习:不要使用JavaScript内置的parseInt()函数,利用map和reduce操作实现一个string2int()函数。
function string2int(s) {
let arr = s.split('');
let newArr = arr.map(item => {
return +item;
});
return newArr.reduce((x, y) => {
return x * 10 + y
})
}
// 测试:
if (string2int('0') === 0 && string2int('12345') === 12345 && string2int('12300') === 12300) {
if (string2int.toString().indexOf('parseInt') !== -1) {
console.log('请勿使用parseInt()!');
} else if (string2int.toString().indexOf('Number') !== -1) {
console.log('请勿使用Number()!');
} else {
console.log('测试通过!');
}
}
else {
console.log('测试失败!');
}