js中的小技巧

js中的小技巧

  • 我的社交平台 有问题可以在这里留言呀
  • github
  • 博客

~~

  • 用于数字取整
  • undefined null NaN 都会变成 0
console.log(~~(11.11));     // 11

&

  • 判断奇偶
  • undefined null NaN “” 都会变成 0
console.log(7 & 1);    // 1
console.log(8 & 1) ;   // 0

!!

  • 转换布尔值
  • undefined null NaN 0 ""都会变成 false
  • [] {} 会变成 true
console.log(!!7);               // true
console.log(!![]);              // true
console.log(!!{});              // true
console.log(!!null);            // false
console.log(!!undefined);       // false

>>

  • 左位移一等于乘二
  • 右位移一等于除二
  • undefined null NaN “” 都会变成 0
console.log(16 >> 1);      // 8
console.log(16 << 1);      // 32

清空数组

let arr = [1];
arr.length = 0;
console.log(arr); // []

生成随机数

0 | Math.random() * 100
new Date % 100 //两位随机数
new Date % 1000 //三位随机数

生成随机字符串

// .substring() 的第二个参数控制取多少位 (最多可取13位)
Math.random().toString(16).substring(2, 15);

创建链接

console.log("Google".link("www.google.com")); // <a href="www.google.com">Google</a>

快速判断IE8以下的浏览器

var isIE8 = !+"1";
console.log(isIE8); // false // Chrome 87

正确处理异常的方法

try {
    // something
} catch (e) {
    window.location.href = "http://stackoverflow.com/search?q=[js]+" +  e.message;
}

参考

  • https://zhuanlan.zhihu.com/p/150556186
  • https://zhuanlan.zhihu.com/p/262533240
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值