前端

How Smart Tools Are Shaping the Future of Creative Work

Eric Chuang
2020-11-07

問題

列出數值的展開形式:將一個數值,以十進位的方式拆解成不同的值相加。譬如 135 會拆解成 100 + 30 + 5。

我的作法

function expandedForm( num ) {
  let arr = [],
      ten = 0;
  while( num > 0 ) {
    arr.push( num % 10 * Math.pow( 10, ten ));
    num = Math.floor( num / 10 );
    ten++;
  }
  return arr.reverse().filter( num => { return num > 0 }).join( ' + ' );
}

投票評選最好的解法

const expandedForm = n => n.toString()
                            .split("")
                            .reverse()
                            .map( (a, i) => a * Math.pow(10, i))
                            .filter(a => a > 0)
                            .reverse()
                            .join(" + ");

改善點

為了測試兩邊的效能相差多少,所以學會了新的偵錯技能:console.time()。

根據 console.time() 的結果,兩種方法執行上相差了 0.03 毫秒左右,也可以說兩者的效能相差了 22%:

expandedForm: 0.11083984375 ms
expandedForm2: 0.086181640625 ms

最主要的差異在於我使用了迴圈來執行運算,而其他人的作法則是將數字轉為字串後,用 map() 的方法一次全部變更。從這次的練習中,我注意到我寫程式的問題在於太急著用「迴圈」的方式來解。

關於陣列的運算,我還是要更熟悉 map()、reverse()、filter() 等等的用法。這也是太過依賴函式庫的我欠缺的練習吧。

用 console.time() 測試執行時間

要在主控台面板中呈現上述訊息,只需要在主控台裡執行以下程式碼即可。透過 console.time() 跟 console.timeEnd() 來測量函式執行的時間。

function expandedForm( num ) {
  let arr = [],
      ten = 0;
  while( num > 0 ) {
    arr.push( num % 10 * Math.pow( 10, ten ));
    num = Math.floor( num / 10 );
    ten++;
  }
  return arr.reverse().filter( num => { return num !== 0 }).join( ' + ' );
}
console.time('test1'); //在主控台要顯示的標籤名稱
expandedForm(1789342003);
console.timeEnd('test1');

function expandedForm2( num ) {
    return num.toString()
              .split("")
              .reverse()
              .map( (a, i) => a * Math.pow(10, i))
              .filter(a => a > 0)
              .reverse()
              .join(" + ");
}
console.time('test2'); //在主控台要顯示的標籤名稱
expandedForm2(1789342003);
console.timeEnd('test2');

Sign up for our newsletter

Subscribe to our newsletter to receive the latest updates, expert insights, and practical tips directly in your inbox. Stay informed with content designed to help you grow.

+480.000 happy customers

Gain more with expert solutions

Unlock the full potential of your business with our expert solutions. Our team provides tailored strategies, professional guidance, and actionable insights to help you achieve better results.

  • Eric Chuang
  • •
  • 2025-01-23
如何同時使用 Webinoly 與 Cloudflare 保護網站安全

在社群夥伴勇哥的文章〈Webinoly 最新版快速安裝〉中,提到使用 Webinoly 來建立 WordPre […]

主機