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.

 

我的答案:

 1 function expandedForm(num) {
 2   // Your code here
 3   var j=0;
 4   var str=num.toString().split("");
 5   var result=[];
 6   for(var i=str.length-1;i>=0;i--){
 7     str[i]=str[i]*Math.pow(10,j);
 8     j++;    
 9     if(str[i]){
10       result=result.concat(str[i]);
11     }
12   }
13    
14   return result.reverse().join(' + ');
15 }

 

优秀答案:

1 const expandedForm = n => n.toString()
2                             .split("")
3                             .reverse()
4                             .map( (a, i) => a * Math.pow(10, i))
5                             .filter(a => a > 0)
6                             .reverse()
7                             .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...infoo...of,for(let i = 0; i < len; i++) 等。在for循环中可以使用 continuebreak 来控制循环。

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); // 创建一个新数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。

 
posted @ 2018-04-03 19:48  小字辈  阅读(607)  评论(0编辑  收藏  举报