js--codewars--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.
我的答案:
1function 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 returnresult.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...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); // 創建一個新數組,新數組中的元素是通過檢查指定數組中符合條件的所有元素。
js--codewars--Write Number in Expanded Form—filters、map、reduce、forEach