Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
內容目錄
列出數值的展開形式:將一個數值,以十進位的方式拆解成不同的值相加。譬如 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.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');