花里花哨的js装逼大法

182 阅读1分钟

前方高能

 1. 史上最快清除缓存大法 

<a href="javascript:alert( 清除成功 );">清除缓存</a>

2. JS 错误处理的方式的正确姿势

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

 3.字符串转数字、数字转字符串

str - 0
num + ''

4.可选的链

const user = {
  employee: {
    name: "Kapil"
  }
};
user.employee?.name;
// Output: "Kapil"
user.employ?.name;
// Output: undefined
user.employ.name
// 输出: VM21616:1 Uncaught TypeError: Cannot read property 'name' of undefined

5.字符串中是否存在某个字符

~'string'.indexOf('y')

6.返回值为null或undefined返回默认值

null ?? 'default'

7.很酷的三元运算

function Fever(temp) {
    return temp > 55 ? '我超大'
      : temp < 55 ? '小于小于!!'
      : temp === 55 ? '我是五五!';
}

// 输出
Fever(55): "我是五五!" Fever(100): "我超大"

8.快速取整

(11.11 >> 0)