codewars--js--Write Number in Expanded Form—filters、map、reduce、forEach
问题描述:
you will be given a number and you will need to return it as a string in Expanded Form. For example:
expandedForm(12); // Should return '10 + 2'
expandedForm(42); // Should return '40 + 2'
expandedForm(70304); // Should return '70000 + 300 + 4'
NOTE: All numbers will be whole numbers greater than 0.
我的答案:
function expandedForm(num) {
// Your code here
var j=0;
var str=num.toString().split("");
var result=[];
for(var i=str.length-1;i>=0;i--){
str[i]=str[i]*Math.pow(10,j);
j++;
if(str[i]){
result=result.concat(str[i]);
}
} return result.reverse().join(' + ');
}
优秀答案:
const expandedForm = n => n.toString()
.split("")
.reverse()
.map( (a, i) => a * Math.pow(10, i))
.filter(a => a > 0)
.reverse()
.join(" + ");
总结:优秀答案同自己的思路一样,但是优秀答案用到了数组的方法filter、map。
filter,map,forEach,reduce都不会改变原数组。
数组的方法 | 作用 |
遍历数组forEach() | 数组的每一个元素都执行一次回调函数 |
filter() | 检测数值元素,并返回符合条件所有元素的数组。 |
map() | 通过指定函数处理数组的每个元素,并返回处理后的数组。 |
reduce() | 将数组元素计算为一个值(从左到右) |
1,forEach遍历数组
[ ].forEach( function ( value, index, array ) { //value:遍历的数组内容, index:对应数组索引, Array:数组本身
// code something
},thisValue);
(1)与for的比较:
for
是循环的基础语法,可以有 for...in
, foo...of
,for(let i = 0; i < len; i++)
等。在for
循环中可以使用 continue
, break
来控制循环。
forEach
可以当做是for(let i = 0; i < len; i++)
的简写,但是不能完成 i + n
这种循环,同时也不支持 continue
和 break
,只能通过 return
来控制循环。另外,使用forEach
的话,是不能退出循环本身的;forEach对于稀疏矩阵处理比较好,不会处理为空的数组。
(2)与map的比较
https://www.cnblogs.com/liuruyi/p/6483526.html
共同点:
1.都是循环遍历数组中的每一项。
2.forEach() 和 map() 里面每一次执行匿名函数都支持3个参数:数组中的当前项item,当前项的索引index,原始数组input。
3.匿名函数中的this都是指Window。
4.只能遍历数组。
不同点:
forEach()没有返回值
map()有返回值
2,map()
[ ].map(function(currentValue,index,arr), thisValue) //返回新数组,数组中的元素为原始数组调用函数处理后的值
3,reduce()
[ ]. reduce( function ( total, currentValue, currentIndex, arr), initialValue); // 返回一个值
4,filter()
[ ] . filter ( function ( currentValue, index, arr), thisValue); // 创建一个新数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
最新文章
- 《Qt Quick 4小时入门》学习笔记3
- 10月24日下午PHP封装
- 【转】logback 常用配置详解(序)logback 简介
- Hook机制里登场的角色
- php设计模式--单例模式
- 据说每个大牛、小牛都应该有自己的库——Event处理
- 第16/24周 SQL Server 2014中的基数计算
- #8.12.16总结#background transition、animation、transform
- JavaScript学习笔记-实现枚举类型,扑克牌应用
- asp.net、 mvc session影响并发
- EasyUI - DataGrid 去右边空白滚动条列 分类: JavaScript 2014-09-03 10:46 1090人阅读 评论(2) 收藏
- Google搜索质量评估员指南
- POJ 1144 Network(Tarjan求割点)
- Html5——地理定位及地图
- SQL语句的执行顺序
- IOS横竖屏控制与事件处理
- JavaScript自学代码--(三)
- leetcode[170]Two Sum III - Data structure design
- OO第一单元总结分析
- php.ini文件下载
热门文章
- Qt Installer Framework翻译(3-4)
- Kafka Topic 体系结构 - 复制 故障转移 并行处理
- Android studio 连接真机
- 使用Razor表达式 举数组和集合 精通ASP-NET-MVC-5-弗瑞曼
- Redis(七):set/sadd/sismember/sinter/sdiffstore 命令源码解析
- php编译完php.ini加载问题-Loaded Configuration File (none)
- Cassandra2.2.10安装过程
- ios---设置UITabBarController的字体颜色和大小
- Shell常用脚本之用户操作
- Leetcode 题目整理-6 Swap Nodes in Pairs &; Remove Duplicates from Sorted Array