JavaScript Useful Code

RGB to Hex via Binary Shifting

1
2
3
function rgbToHex(r, g, b) {
return "#" + ((1<<24)+(r<<16)+(g<<8)+b).toString(16).slice(1);
}

快速取整

1
2
3
let a = ~~2.33;
let b = 2.33 | 0;
let c = 2.33 >> 0;

字符串与数字快速转换

1
2
+'10' //10
(10)["toString"]() //"10"

优雅的实现金钱格式化

1
2
3
var test1 = "1234567890";
var format = test1.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
console.log(format);//1,234,567,890

正则表示式学习资源
MDN