iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 9
1
自我挑戰組

利用30分鐘~想一個前端問題系列 第 9

利用30分鐘~想一個前端問題 Day9--[both]

Returns true if both functions return true for a given set of arguments, false otherwise.

Use the logical and (&&) operator on the result of calling the two functions with the supplied args.

const both = (f, g) => (...args) => f(...args) && g(...args);

const isEven = num => num % 2 === 0;
const isPositive = num => num > 0;
const isPositiveEven = both(isEven, isPositive);
isPositiveEven(4); // true
isPositiveEven(-2); // false

分析點

我們設定兩個function,設定兩個不同條件一個是大於零 另外一個是設定2的倍數,可把兩個條件的function 合併在一起

const both = (f, g) => (...args) => f(...args) && g(...args);

裡面的 (...args) 就是運用了展開運算子 把陣列展開,傳入函式之中

function sum(a, b, c) {
  return a + b + c;
}

var args = [1, 2, 3];
console.log(sum(...args)); // 6

參考資料

MDN Object.keys()

邁向 JavaScript 勇者之路


上一篇
利用30分鐘~想一個前端問題 Day8-4 JavaScript Array methods you must know
下一篇
利用30分鐘~想一個前端問題 Day10--maxDate
系列文
利用30分鐘~想一個前端問題30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言