Map and reduce in JavaScript

Source: Internet
Author: User

Today, while watching the JS tutorial "official website of Liao Xuefeng", I saw the map and reduce. One of the exercises is: Do not use JS built-in parseInt() functions, using the map and reduce operations to implement a string2int() function (the string is converted to an array, and then converted to a number from arr[0] to Arr[arr. (length-1)]. For example: [1, 3, 5, 7, 9] transform into an integer 13579.

My solution:

function tonum (str)        {            var arr=[];              for (var i=0;i<str.length;i++)            {                Arr.push (str[i]);            }             var num=arr.reduce (function(x, y)            {                return x * + y;            })            alert (num);        }       Tonum (' 123 ');

But the above results pop up with "10203". After the test, there are several reasons:

1, the ARR array for the For loop, gets [' 1 ', ' 2 ', ' 3 '] instead of [All-in-one]. That is, each element in the array is a string, not a number.

function Tonum (str)    {    var arr=[];    for (Var i=0;i<str.length;i++)    {    arr.push (str[i]);    }    return arr;    }       Tonum (' 123 ');//Return ["1", "2", "3"]

2, strings and numbers are subtraction to get a number, string and string addition, is the way strings are concatenated, the resulting string is still.

"1" *10+2;//return 12 "1" *10+ "2";//Return "102"

Correction Scheme one: subtract the string from the first array in the For loop and 0, get an array that is a number, and then apply the reduce function to the array.

function Tonum (str)    {    var arr=[];    for (Var i=0;i<str.length;i++)    {    arr.push (str[i]);    }    var arrn=arr.map (function (x) {return x-0})    var num=arrn.reduce (function [x, y)    {    return x * + y;    })    alert (num);    }       Tonum (' 123 ');

To simplify again, take advantage of the split method of the string:

function Tonum (str)    {    var arr=str.split ('); Each element in the array returned by the//split method is still a string    var arrn=arr.map (function (x) { Return x-0})    var num=arrn.reduce (function (x, y)    {    return x * + y;    })    alert (num);    } Tonum (' 123 ');

Exercise two: "The user entered the non-standard English name, the first letter capitalized, other lowercase canonical name." Input: [‘adam‘, ‘LISA‘, ‘barT‘] , Output: [‘Adam‘, ‘Lisa‘, ‘Bart‘] . ”

My solution:

function Norm (arr) {var arrn=[];    for (Var i=0;i<arr.length;i++)    {    Arrn.push (    arr[i][0].touppercase () +    arr[i].substring (1). toLowerCase ());            }    alert (ARRN);} Norm ([' A dam ', ' Lisa ', ' Bart ']);

  

  

Supplement: About substring () and slice ().

SUBSTRING (): the substring () method is used to extract the character of a string intermediary between two specified subscripts.

Syntax:stringobject. substring (start,stop). The substring returned by the substring () method includes the character at start , but does not include the character at the stop .

Slice (): the Slice () method returns the selected element from an existing array .

Syntax: Arrayobject.slice (start,end). Returns a new array containing elements from start to end ( excluding the element) from the Arrayobject.

 

Map and reduce in JavaScript

Related Article

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.