Open azole opened 1 month ago
// Basic
// Method1: Use Reduce Function
function sum_with_reduce(ary) {
let result = ary.reduce((accumulator, current) => accumulator + current);
return result;
}
console.log(sum_with_reduce([1, 5, 3, 2])); // 11
// Method2: Use forEach() Function function sum_with_for_each(ary) { let sum = 0; ary.forEach((element) => { sum += element; }); return sum; } console.log(sum_with_for_each([1, 5, 3, 2])); // 11
// Method3: Use join() & eval() function sum_with_eval_and_join(ary) { let result = eval(ary.join("+")); return result; } console.log(sum_with_eval_and_join([1, 5, 3, 2])); // 11
// Method4: Use lodash var _ = require("lodash"); function sum_withlodash(ary) { let result = .sum(ary); return result; } console.log(sum_with_lodash([1, 5, 3, 2])); // 11
## fib
1. 把程式碼變得更簡潔:把 (n==1) 和 (n==2) 的條件判斷寫在一起,修改過後如下:
```javascript
function fib(n) {
// TODO: implement fibonacci
if (n == 0) {
return 0;
} else if (n == 1 || n == 2) {
return 1;
} else {
return fib(n - 1) + fib(n - 2);
}
}
function fib_2(n) {
let arr = [1, 1];
if (n == 0) {
return 0;
}
if (n == 1 || n == 2) {
return 1;
}
for (let i = 3; i <= n; i++) {
let tmp = arr[i - 3] + arr[i - 2];
arr.push(tmp);
}
return arr[n - 1];
}
#items;
代表把 items 設為 private,沒辦法直接被外部 class 訪問 (老師不好意思我本來以為你是在問 //TODO
是甚麼意思><)// 檢查 stack 是否為空
isEmpty() {
// TODO
return this.#items.length == 0;
}
undefined
才是正確的
readme
ok
sum
fib
stack
undefine
應該是undefined
?上述問題可以回覆在 issue 裡,要不要改回去原檔案可以自行判斷,我會建議可以修改回去,保持作業的完整性與品質。