Javascript 好玩的10个代码块

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)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值