This exercise is from the Liaoche JS tutorial. The answer is self-written.
function functions are described as follows:
Turn a string 13579
into a Array
-- [1, 3, 5, 7, 9]
and then use reduce()
it to write a function that converts the string to number.
The function code is as follows:
' Use strict ';
function String2int (s) {
var arr = [];
The string is converted to an array, but each element of the arrays that this method gets is still a string
for (var i = 0; i < s.length; ++i) {
Arr[i] = s[i];
}
Defines a new array to receive an array of integers for each element that is converted from the previous array
var new_arr = [];
New_arr = Arr.map (function (elem) {
return +elem; ' + ' can convert any non-digital to a number
});
Convert an array to a coherent integer
Return New_arr.reduce (function (x, y) {
return x * ten + y;
});
}
The test code is as follows:
Test: if (String2int (' 0 ') = = = 0 && string2int (' 12345 ') = = = 12345 && string2int (' 12300 ') = = = = 12300) { I F (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 (' Test pass! ');} } else { console.log (' Test failed! ');}
Tested to meet the requirements.
Exercise: Do not use the JavaScript built-in parseint () function to implement a string2int () function with map and reduce operations