Javascript 好玩的10个代码块
1.单行写一个评级组件
"★★★★★☆☆☆☆☆".slice(5 – rate, 10 – rate)
2.Javascirpt错误处理的方式的正确方式
try {
something
} catch (e) {
window.location.href =
"http://stackoverflow.com/search?q=[js]+" +
e.message;
}
3.一个简单的🌈边框小语句
[].forEach.call($$("*"),function(a){
a.style.outline="1px solid #"+(~~(Math.random()*(1<<24))).toString(16)
})
正常语言如下:
Array.prototype.forEach.call(document.querySelectorAll('*'),
dom => dom.style.outline = `1px solid #${parseInt(Math.random() *
Math.pow(2,24)).toString(16)}`)
不得不说 $$()
真的好用
4.优雅的取随机字符串
Math.random().toString(16).substring(2)
Math.random().toString(36).substring(2)
5.匿名函数自动执行
( function() {}() );
( function() {} )();
[ function() {}() ];
~ function() {}();
! function() {}();
+ function() {}();
- function() {}();
delete function() {}();
typeof function() {}();
void function() {}();
new function() {}();
new function() {};
var f = function() {}();
1, function() {}();
1 ^ function() {}();
1 > function() {}();
6.另一种🐮🍺的设定undefined
被鄙视的写法:
var data = undefined
真正🐮🍺的写法:
var data = void 0; // undefined
别问,问了就是兼容早起ECMAScript标准中没有undefined属性
7.优雅的取整
let a = ~~2.33
let b = 2.33 | 0
let c = 2.33 >> 0
8.清除缓存
一键清除缓存,用户直说真的好用🐮,隐私保护必备按钮。
<button onclick="alert('清除成功')">清除缓存</button>
9.互换值
弟弟🧍♂️写法
temp = a;
a = b;
b = temp;
大佬写法
[a,b] = [b,a]
10.生成长度m,值都为n的数组
Array(m).fill(n)