iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 10
0
自我挑戰組

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

利用30分鐘~想一個前端問題 Day10--maxDate

  • 分享至 

  • twitterImage
  •  

maxDate

Returns the maximum of the given dates.

Use the ES6 spread syntax with Math.max to find the maximum date value, new Date() to convert it to a Date object.

const maxDate = dates => new Date(Math.max(...dates));
EXAMPLES
const array = [
  new Date(2017, 4, 13),
  new Date(2018, 2, 12),
  new Date(2016, 0, 10),
  new Date(2016, 0, 9)
];
maxDate(array); // 2018-03-11T22:00:00.000Z

使用 es6 的 展開(spread syntax) 針對 Math.max()尋找時間最晚的日期,再用 Date() 方法  轉換日期物件。

記憶點:

1.spread syntax
ES6 引入了新的運算子 (operator) ... (三個點號) 來表示展開或其餘運算子。

function foo(x, y, z) {
    console.log(x, y, z);
}

var arr = [1, 2, 3];

// 輸出 1 2 3
// 等同於執行 foo(1, 2, 3)
foo(...arr);

2.new Date()

Date() 物件,使用內件的日期物件與方法、可以取得與操作日期時間。日期物件有多種的方法來設定及取得。

var d = new Date();
console.log(d); // Thu Sep 17 2020 09:18:47 GMT+0800 (台北標準時間)

至於格式化方法網路上有很多方法可以參考。

3.Math.max()

Math.max() 可以比較數字裡面的最大值,但不能單純直接放進去陣列,要用 展開方法

Math.max(10, 20);   //  20
Math.max(-10, -20); // -10
Math.max(-10, 20);  //  20


var numbers = [1, 2, 3, 4];
Math.max(...numbers) // 4
Math.min(...numbers) // 1

參考資料

MDN-Math.max()


上一篇
利用30分鐘~想一個前端問題 Day9--[both]
下一篇
利用30分鐘~想一個前端問題 Day11-nthElement
系列文
利用30分鐘~想一個前端問題30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言