高阶函数 map/reduce页面习题

简单来说,map函数就是把数组元素一个一个取出来玩,reduce函数就是按顺序去前两个玩,玩完了把结果再和下一个元素放在一起玩。

1.利用reduce求积

'use strict';

function product(arr) {
    return arr.reduce(function(x,y){return x*y});
}

// 测试:
if (product([1, 2, 3, 4]) === 24 && product([0, 1, 2]) === 0 && product([99, 88, 77, 66]) === 44274384) {
    console.log('测试通过!');
}
else {
    console.log('测试失败!');
}
View Code

2.不使用JavaScript内置parseInt()函数,利用map和reduce函数实现一个函数String2Int()

'use strict';

function string2int(s) {
    //return s*1;
    //第一步:字符串分离为为字符数组
    str = s.split("");
    //第二步:数组转换
    str1 = str.map(function(x){return x-'0';});
    //第三步:1,2,3,4,5==>12345
    var result = str1.reduce(function(x,y){return x*10+y;});
    return result;
}

// 测试:
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('测试失败!');
}
View Code

3.名称规范:首字母大写Input:['adam', 'LISA', 'barT'],Output:['Adam', 'Lisa', 'Bart']

'use strict'
function normalize(arr) {
    var result = arr.map(function(x){
    //思路:取出首字母大写,取出剩余字母小写,再结合
    var UpperHead = x.substring(0,1).toUpperCase().substring(0,1);
    var LowerTail = x.substring(1).toLowerCase().substring(1);
    return UpperHead+LowerTail;
    });
    return result;
}
 
// 测试:
if (normalize(['adam', 'LISA', 'barT']).toString() === ['Adam', 'Lisa', 'Bart'].toString()) {
    console.log('测试通过!');
}
else {
    console.log('测试失败!');
}
View Code


想了想,上面的代码不好,在处理字母时应该先取字母再处理

'use strict'
function normalize(arr) {
    var result = arr.map(function(x){
    //思路:取出首字母大写,取出剩余字母小写,再结合
    var UpperHead = x.substring(0,1).toUpperCase();
    var LowerTail = x.substring(1).toLowerCase();
    return UpperHead+LowerTail;
    });
    return result;
}
 
// 测试:
if (normalize(['adam', 'LISA', 'barT']).toString() === ['Adam', 'Lisa', 'Bart'].toString()) {
    console.log('测试通过!');
}
else {
    console.log('测试失败!');
}
View Code

4.小明字符串变整数

'use strict';

var arr = ['1', '2', '3'];
var r;
r = arr.map(function(x){return x-'0';});
console.log(r);
View Code

猜你喜欢

转载自www.cnblogs.com/zhangzemin/p/9317085.html