练习1:利用reduce()
求积:
代码如下:
function Product(arr){ //乘积函数
var result;
result = arr.reduce(function(x,y){ //数组中的每一项相乘
return x*y;
});
return result;
}
//test
if (Product([1, 4, 7]) === 28 && Product([0, 1, 2]) === 0 && Product([99,88,77]) === 670824) {
console.log('通过测试!');
} else {
console.log('测试失败!');
}
练习2:利用map和reduce操作实现一个string2int()
函数。(不要使用JavaScript内置的parseInt()
函数和number())
代码如下:
//将字符串转化成数字,例如 若输入'1467',则输出1467(number类型)
function string2int(s){
var str = []; //存储字符串中每一个字符的数组
var num = []; //存储number类型的数组
var result;
for(var i = 0; i < s.length; i++){ //循环存储字符串中每一个字符,存在数组里
str[i] = s.charAt(i);
}
num = str.map(function(index){
return +index; //将string 转换成number 或者用 (i-0) 得到number类型
});
result = num.reduce(function(x, y){ //返回一个数
return x*10+y;
});
return result;
}
//test
if(string2int('0') === 0 && string2int('1234') === 1234 && string2int('1200') === 1200){
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('测试失败!');
}