學習重點:map( )、floatmap( )、簡易箭頭函式
題目連結
題目摘要
Given two integers m, n (1 <= m <= n) we want to find all integers between m and n whose sum of squared divisors is itself a square. 42 is such a number.
The result will be an array, each subarray having two elements, first the number whose squared divisors is a square and then the sum of the squared divisors.
Examples:
Divisors of 42 are : 1, 2, 3, 6, 7, 14, 21, 42. These divisors squared are: 1, 4, 9, 36, 49, 196, 441, 1764. The sum of the squared divisors is 2500 which is 50 * 50, a square!
list_squared(42, 250) --> [[42, 2500], [246, 84100]]
從題目敘述可以明白:
題目會給隨機兩的數字,輸出兩個數字中,因數的平方加總開根號為整數的數值
題目做法
我的作法:
因為 MDN 和許多 Codewars 上的解答都常常出現箭頭函數
箭頭函數是 ES6 的寫法
的確時代的進步,JS 都出到不知道幾代了,我還在 ES5 原地踏步真的是很慚愧
但我還有很多基礎觀念不懂一下子跳到 ES6 感覺不太踏實
今天就當偷跑一回
我是看這個簡中的版本簡單學了一下下
簡單來說就是:
ES5
var num = function (要帶入的參數名稱){ return 要執行的內容 }
ES6
var num =(要帶入的參數名稱)=> { 要執行的內容 }
var num =(要帶入的參數名稱)=> { 要執行的內容
return 多行要加return}
但箭頭函數不只是這麼簡單而已,只是我其他觀念還不熟先簡單瞭解了一下Q
希望能幫助到看不懂箭頭函數的同學了解上面的程式碼
其中,要講的函式是 map( )
、 floatMap( )
flatMap( ) 和 map( ) 一樣,依照 callback 函數依序處理陣列元素,並壓縮成陣列回傳
array.flatMap(function callback(current_value, index, Array)
{
// It returns the new array's elements.
}[, thisArg])
callback 函數的參數分為以下三種:
- current_value: 目前正在處理的元素變數名稱 (required)
- index: 目前正在處理的元素變數索引 (optional)
- Array: 被調用的陣列變數名稱 (optional)
另外
- thisArg:執行 callback 函數可用的 this 值
floatMap( ) 和
map( )有什麼差別
呢?
他們用法差不多,差別只是在:
flatMap(x => [x * x]);
//[1,4,9]
//
map(x => [x * x]);[[1],[4],[9]]
//
map(x => x * x);[1,4,9]
但 Codewars 似乎不支援 flatMap( )
?
會出現「 TypeError: divisor.flatMap is not a function 」的錯誤訊息
我偷懶用 Chrome 的 Console 試了一下,都可以成功運行呀?
真奇怪?
以上就是最近的程式練習心得
希望我可以早日學完 ES5 的概念
不然我真的在史前時代太久了點~
有錯誤或是要分享的都歡迎留言
或是曾經在 Codewars 使用 flatMap( )
失敗的都可以讓我知道我不孤單
到底為什麼我無法使用呢?
拍個手讓我知道,這個文章對你們有幫助 ♥(´∀` )人