JS短小代码

评级组件:自定义rate(1-5)

"★★★★★☆☆☆☆☆".slice(5 - rate, 10 - rate);

快速取整

console.log(~~47.11) // -> 47

console.log(~~1.9999) // -> 1

console.log(~~[])    // -> 0

------------

console.log(20.15|0);          // -> 20

console.log((-20.15)|0);      // -> -20

------------

console.log(20.15^0);          // -> 20

console.log((-20.15)^0);      // -> -20

------------

console.log(20.15 < < 0);    // -> 20

console.log((-20.15) < < 0);  //-20

处理比较大的数字时(当数字范围超出 ±2^31−1 即:2147483647),会有一些异常情况。使用的时候明确的检查输入数值的范围。

SB

(!(~+)+{})[--[~+""][+[]]*[~+[]] + ~~!+]+({}+)[[~!+[]]*~+]

NB

([[]]+)[+!![]]+(+{})[!+[]+!!]

JS处理错误

try {

something

} catch (e) {

window.location.href =

"[http://stackoverflow.com/search?q=](https://link.jianshu.com/?t=https://link.zhihu.com/?target=http%3A//stackoverflow.com/search%3Fq%3D)*[js]+" +*

e.message;

}

盒子模型

[].forEach.call($$("*"),function(a){

a.style.outline="1px solid #"+(~~(Math.random()*(1<<24))).toString(16)

})

整数交换

a ^= b;

b ^= a;

a ^= b;

金钱格式化

正则

var test1 = '1234567890'

var format = test1.replace(/\B(?=(\d{3})+(?!\d))/g, ',')

console.log(format) // 1,234,567,890

非正则

function formatCash(str) {

return str.split('').reverse().reduce((prev, next, index) => {

return ((index % 3) ? next : (next + ',')) + prev

})

}

console.log(formatCash('1234567890')) // 1,234,567,890

你可能感兴趣的:(JS短小代码)