JavaScript 常用优化技巧

39 阅读1分钟

简化或运算符

if (variable1 !== null || variable1 !== undefined || variable1 !== '') {
     let variable2 = variable1;
}

优化后

const variable2 = variable1  || 'newValue';

布尔值简写

if (condition === true) { // do sth. }
if (condition !== true) { // do sth. }

优化后

if (condition) { // do sth. }
if (!condition) { // do sth. }

对象赋值简写

const x = 10, y = 89;
const obj = { x: x, y: y };

优化后

const obj = { x, y };

函数参数默认值

function getVal (a, b) {
  if (a === undefined) a = 3;
  if (a === undefined) b = 100;
  return a * b;
}

优化后

function getVal (a = 3, b = 100) {
  return a * b;
}

函数参数必填

function foo(bar) {
  if(bar === undefined) {
    throw new Error('Missing parameter!');
  }
  return bar;
}

优化后

mandatory = () => {
  throw new Error('Missing parameter!');
}
foo = (bar = mandatory()) => {
  return bar;
}

三目运算符

const x = 20;
let answer;
if (x > 10) {
    answer = "greater than 10";
} else {
    answer =  "less than 10";
}

优化后

const answer = x > 10 ? "greater than 10" : "less than 10";

巧用e简化0的个数

let x = 10000;

优化后

let x = 1e4;

Math.pow()简写

const x = Math.pow(2,3); // 8

优化后

const x = 2**3; // 8

let赋值简写

let x;
let y;
let z = 3;

优化后

let x, y, z=3;

模板语法

const url = 'http://' + host + ':' + port + '/' + database;

优化后

const url = `http://${host}:${port}/${database}`;