Liao Xuefeng blog JS-map / reduce problem solution

Using reduce () quadrature:

 

'use strict';

 

function product(arr) {

return arr.reduce(function(x, y) {

return x * y;

});

}

 

Do not use the JavaScript built-in parseInt () function, using the map and reduce operations to achieve a string2int () function:

 

'use strict';

 

function string2int(s) {

var = strArr s.split ( '')

var strArrNum = strArr.map(function(str) {

return +str

})

var num = strArrNum.reduce(function(x, y) {

return x * 10 + y

})

return num

}

 

Please enter the user's non-standard English name, becomes the first letter capitalized, other specifications lowercase names. Input: [ 'adam', 'LISA', 'barT'], output: [ 'Adam', 'Lisa', 'Bart'].

 

Alone with a good map and toCase () conversion of Series

 

'use strict'

 

function normalize(arr) {

return arr.map(function(s) {

s = s.toLowerCase();

var temp = [... s]; // note here, not s [0] = s [0] .toUpperCase (), this function may not operate for the individual strings, and need to be converted to an array of characters

temp[0] = temp[0].toUpperCase();

return s = temp.join ( ""); // map function in vivo remember plus return, otherwise you perform a function after releasing it got nothing.

});

}

 

Splicing process directly substring

 

'use strict'

 

function normalize(arr) {

return arr.map(function(s) {

return s.slice(0, 1).toUpperCase() + s.substring(1).toLowerCase();

})

}

 

stringObj.slice(start, [end])

If start is negative, the process as start + length, where length is the length of the array. If end is negative, it will be treated as an end + length, where length is the length of the array. If you omit end, then slice extraction continues to the end of arrayObj. If end occurs before start, do not copy any elements to the new array.

 

strVariable.substring(start, end)

If the start or end NaN or negative, then it is replaced by 0.

Substring length equal to the absolute difference between the start and the end. For example, the length strvar.substring (0, 3), and strvar.substring (3, 0) returns the substring is 3.

 

slice array can operate, substring not

 

Beacon Course

Guess you like

Origin www.cnblogs.com/YuelinWang/p/12620879.html