Exercise: Do not use the JavaScript built-in parseint () function to implement a string2int () function with map and reduce operations

Source: Internet
Author: User
Tags string to number

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.