原文git地址
https://github.com/TigerHee/shareJS
小數(shù)取整:
1.234 | 0
~~1.234
1.234 >> 0
妙用隱式轉(zhuǎn)換:
數(shù)字字符串轉(zhuǎn)number:
+'123'
new Date轉(zhuǎn)時(shí)間戳:
+new Date()
數(shù)組/多維數(shù)組轉(zhuǎn)逗號(hào)分隔字符串:
''+[1, 2 , 3, 3, [2, 3, 4]]
解構(gòu):
交換a,b的值:
var a=1;
var b=2;
[a, b] = [b, a];
console.log('a ===', a);
console.log('b ===', b);
擴(kuò)展運(yùn)算符:
取數(shù)組最大值:
Math.max(...[1,2,3])
生成時(shí)間:
new Date(...[2018,6,4])
字符串轉(zhuǎn)數(shù)組:
method 1:
[...'string']
method 2:
Array.from('string')
合并對(duì)象:
let obj1 = {a:1, b:2};
let obj2 = {b:3, c:4};
Object.assign(obj1, obj2)
????等同于
{...obj1, ...obj2}
常用方法:
數(shù)字前補(bǔ)0:
preFixNum(num, length) {
????return (Array(length).join('0') + num).slice(-length);
}
數(shù)組元素為對(duì)象的去重:
[...new Set(arr.map(v => JSON.stringify(v)))].map(v => JSON.parse(v))
數(shù)組求和:
var arr = [1,2,3,4,5];
method 1:
var sum = eval(arr.join('+'));
method 2:
var sum = arr.reduce((prev,cur) => prev + cur);
金錢(qián)格式化:
let money = 11111;
method 1:
money.toLocaleString('en-US');
method 2:
Intl.NumberFormat().format(money);
method 3:
String(money).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
短路邏輯代替if:
isTrue && console.log(1);
RGB to Hex:
function RGBtoHEX(rgb){
????return ((1<<24) + (rgb.r<<16) + (rgb.g<<8) + rgb.b).toString(16).substr(1);
}
生成指定長(zhǎng)度數(shù)組:
Array.from(new Array(10).keys());
正則進(jìn)階:
捕獲括號(hào):
匹配 'tigerHee' 并且記住匹配項(xiàng)
/(tigerHee)/
非捕獲括號(hào):
匹配 'tigerHee' 但是不記住匹配項(xiàng)
/(?:tigerHee)/
先行斷言:
匹配'tiger'僅僅當(dāng)'tiger'后面跟著'Hee'
/tiger(?=Hee)/
后行斷言:
匹配'Hee'僅僅當(dāng)'Hee'前面是'tiger'
/(?<=tiger)Hee/
正向否定查找:
匹配'tiger'僅僅當(dāng)'tiger'后面不跟著'java'
/tiger(?!java)/