Math / Date

Method
example

Number.isNaN(val)

return Boolean

Number.isNaN(1) // false

Number.MAX_SAFE_INTEGER

瀏覽器可以存的最大數字

sumOfDigit

18 : 1+8 = 9 20: 2+0 = 2

方法
範例

笨方法

聰明

笨方法:

  • 先轉字串 "18"'

  • 轉 Array: ["1", "8"]

  • 變 Number [1, 8]

  • 再相加 9

let sumOfDigit = 
nums[i].toString()
.split('')
.map(num => Number(num))
.reduce((cur,acc) => cur + acc, 0)

較好方法

Math

  • + , 字串變數字 ''

  • Math.pow() 平方,ex. Math.pow(5, 2) = 25

  • Math.abs(x) 絕對值, ex Math.abs(-3) = 3

  • Math.sqrt(x) 平方根 ex. Math.sqrt(9) = 3

  • Number.MIN_SAFE_INTEGER

  • Number.MAN_SAFE_INTEGER

  • Math.random(), ex. 1 - 5 , 1 + Math.floor(Math.random()*5)

  • toString(2) 十進位轉二進位

Bitwise operators 位元運算子

看起來跟邏輯運算子很像 (&&、 ||)? 完全不一樣啊!!他是在處理二進位的事,有些題目真的會大大減少撰寫行數.倒是平常寫前端還真的從來沒用到過.

  • & (AND)

    bit1 & bit2 : 當兩個位元都是1時,回傳1。不是的話就回傳 0

  • | (OR)

bit1 | bit2 : 其中一個位元是1時,回傳1。

  • ^ (XOR)

bit1 ^ bit2 : 當兩個位元一樣時回傳0,不一樣時回傳1。實務運用可以參考 # 136

  • 交换律:a ^ b ^ c <=> a ^ c ^ b

  • 任何数于0异或为任何数 0 ^ n => n

  • 相同的数可以等於 0: n ^ n => 0

Date

  • new Date() // Mon Oct 14 2019 15:40:54 GMT-0700 (太平洋夏令時間) {}

  • new Date('1990-10-27') // Fri Oct 26 1990 17:00:00 GMT-0700 (太平洋夏令時間) {}

Method

getDate()

14 幾號

getDay()

1 星期幾

getFullYear()

2019 幾年

getHours()

15 幾點

getMilliseconds()

977

getMinutes()

40 幾分

getMonth()

9 幾月

getSeconds()

40 幾秒

getTime()

Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC (negative for prior times).

1571093188494

Last updated

Was this helpful?