JavaScript中自带的 reduce()方法使用示例详解
作者:fangfan 时间:2024-02-24 09:37:11
1.方法说明 , Array的reduce()把一个函数作用在这个Array的[x1, x2, x3...]上,这个函数必须接收两个参数,reduce()把结果继续和序列的下一个元素做累积计算,其效果就是:
[x1, x2, x3, x4].reduce(f) = f(f(f(x1, x2), x3), x4)
2. 使用示例
'use strict';
function string2int(s){
if(!s){
alert('the params empty');
return;
}
if(s.length===1){
return s*1;
}
var arr = [];
for(var i=0; i<s.length; i++){
arr.push(s.substr(i, 1)*1);
}
return arr.reduce(function(x, y){
return x*10 + y;
});
}
// 测试:
if (string2int('0') === 0 && string2int('12345') === 12345 && string2int('12300') === 12300) {
if (string2int.toString().indexOf('parseInt') !== -1) {
alert('请勿使用parseInt()!');
} else if (string2int.toString().indexOf('Number') !== -1) {
alert('请勿使用Number()!');
} else {
alert('测试通过!');
}
}
else {
alert('测试失败!');
}
以上所述是小编给大家介绍的JavaScript中自带的 reduce()方法使用示例详解网站的支持!
来源:http://www.cnblogs.com/rocky-fang/archive/2016/08/10/5755755.html
标签:js,reduce
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
PHP删除数组中指定值的元素常用方法实例分析【4种方法】
2024-06-05 09:51:58
通过python+selenium3实现浏览器刷简书文章阅读量
2022-11-09 09:04:37
3个用于数据科学的顶级Python库
2022-09-25 15:26:45
![](https://img.aspxhome.com/file/2023/9/97519_0s.png)
解决Vue不能检测数组或对象变动的问题
2024-04-27 15:59:40
javascript一个无懈可击的实例化XMLHttpRequest的方法
2024-04-16 09:49:19
python入门jupyter基础操作及文本用法
2022-02-13 21:56:29
![](https://img.aspxhome.com/file/2023/3/95593_0s.png)
pytorch中的自定义数据处理详解
2023-08-21 09:31:35
pytest中配置文件pytest.ini使用
2021-01-22 17:04:02
PHP实现执行外部程序的方法详解
2023-09-08 02:03:46
![](https://img.aspxhome.com/file/2023/8/55618_0s.png)
python unittest实现api自动化测试
2022-12-05 09:52:37
如何把外网python虚拟环境迁移到内网
2021-12-28 14:08:13
关闭窗口时保存数据的办法
2009-02-19 13:39:00
Python实现自动玩贪吃蛇程序
2021-07-27 19:01:47
![](https://img.aspxhome.com/file/2023/0/127630_0s.gif)
python实现的简单FTP上传下载文件实例
2022-12-29 13:17:42
SQL Server日志清除的两种方法教程简介
2008-05-04 20:59:00
巧妙的自关联运用
2012-10-07 10:55:58
vue+element树组件 实现树懒加载的过程详解
2024-05-25 15:19:36
![](https://img.aspxhome.com/file/2023/7/123707_0s.png)
Python写一个简单的在线编辑器
2022-07-26 22:49:17
![](https://img.aspxhome.com/file/2023/2/133862_0s.png)
django 扩展user用户字段inlines方式
2022-02-28 00:50:14
Python获取二维矩阵每列最大值的方法
2022-08-28 00:26:16