Math / Date
sumOfDigit
18 : 1+8 = 9 20: 2+0 = 2
笨方法
let sumOfDigit =
nums[i].toString()
.split('')
.map(num => Number(num))
.reduce((cur,acc) => cur + acc, 0)
聰明
let sum = 0
while (value) {
sum += value % 10;
value = Math.floor(value / 10);
}
笨方法:
先轉字串 "18"'
轉 Array: ["1", "8"]
變 Number [1, 8]
再相加 9
let sumOfDigit =
nums[i].toString()
.split('')
.map(num => Number(num))
.reduce((cur,acc) => cur + acc, 0)
較好方法
function getSumofDigit (value){
let sum = 0
while (value) {
sum += value % 10;
value = Math.floor(value / 10);
}
return sum
}
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)
Math.floor(Math.random()*4)// 0 - 3
Math.floor(Math.random()*5)// 0 - 4
toString(2) 十進位轉二進位
let number = 9;
number.toString(2); // "1001"
Bitwise operators 位元運算子
看起來跟邏輯運算子很像 (&&、 ||)? 完全不一樣啊!!他是在處理二進位的事,有些題目真的會大大減少撰寫行數.倒是平常寫前端還真的從來沒用到過.
// 十轉二
(96).toString(2)
// 二轉十
parseInt('1100', 2)
& (AND)
bit1 & bit2 : 當兩個位元都是1時,回傳1。不是的話就回傳 0
. 9 (base 10) = 1001 (base 2)
14 (base 10) = 1110 (base 2)
--------------------------------
14 & 9 (base 10) = 1000 (base 2) = 8 (base 10)

| (OR)
bit1 | bit2 : 其中一個位元是1時,回傳1。
. 9 (base 10) = 1001 (base 2)
14 (base 10) = 1110 (base 2)
--------------------------------
14 | 9 (base 10) = 1111 (base 2) = 15 (base 10)
^ (XOR)
bit1 ^ bit2 : 當兩個位元一樣時回傳0,不一樣時回傳1。實務運用可以參考 # 136
9 (base 10) = 1001 (base 2)
14 (base 10) = 1110 (base 2)
--------------------------------
14 ^ 9 (base 10) = 0111 (base 2) = 7 (base 10)
交换律:a ^ b ^ c <=> a ^ c ^ b
任何数于0异或为任何数 0 ^ n => n
相同的数可以等於 0: n ^ n => 0
所以 [4,1,2,1,2]
4 ^ 1 ^ 2 ^ 1 ^ 2
== 1 ^ 1 ^ 2 ^ 2 ^ 4
== 0 ^ 0 ^ 4
== 4
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?