食無魚
open main menu

Js 小技巧

/ 3 min read

  • 多重判断

    // no
    if (x === "abc" || x === "def" || x === "ghi" || x === "jkl") {
    }
    // yes
    if (["abc", "def", "ghi", "jkl"].includes(x)) {
      //logic
    }
    
  • 空值检查

// Longhand
if (test1 !== null || test1 !== undefined || test1 !== "") {
  let test2 = test1;
}
// Shorthand
let test2 = test1 || "";
let test2 = test2 ?? "";
  • 多变量赋值
//Longhand
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;
//Shorthand
let [test1, test2, test3] = [1, 2, 3];
  • 判断”,null, undefined
// Longhand
  if (test1 === true) or if (test1 !== "") or if (test1 !== null)
// Shorthand
if (test1)
  • true 并执行
//Longhand
if (test1) {
  callMethod();
}
//Shorthand
test1 && callMethod();
  • forEach 循环
// Longhand
for (var i = 0; i < testData.length; i++)
// Shorthand
for (let i in testData) or  for (let i of testData)
  • 三元函数调用
// Longhand
function test1() {
  console.log("test1");
}
function test2() {
  console.log("test2");
}
var test3 = 1;
if (test3 == 1) {
  test1();
} else {
  test2();
}
// Shorthand
(test3 === 1 ? test1 : test2)();
  • switch 简化
// Longhand
switch (data) {
  case 1:
    test1();
    break;
  case 2:
    test2();
    break;
  case 3:
    test();
    break;
  // ...
}
// Shorthand
var data = {
  1: test1,
  2: test2,
  3: test,
};
data[something] && data[something]();
  • 隐式返回
//longhand
function calculate(diameter) {
  return Math.PI * diameter
}
//shorthand
calculate = diameter => (
  Math.PI * diameter;
)
  • 指数表示法
// Longhand
for (var i = 0; i < 10000; i++) { ... }
// Shorthand
for (var i = 0; i < 1e4; i++) { ... }
  • 对象属性赋值
let test1 = "a";
let test2 = "b";
//Longhand
let obj = { test1: test1, test2: test2 };
//Shorthand
let obj = { test1, test2 };
  • 将字符串转成数字
//Longhand
let test1 = parseInt("123");
let test2 = parseFloat("12.3");
//Shorthand
let test1 = +"123";
let test2 = +"12.3";
  • 数组 find 简化
const data = [
  {
    type: "test1",
    name: "abc",
  },
  {
    type: "test2",
    name: "cde",
  },
  {
    type: "test1",
    name: "fgh",
  },
];
function findtest1(name) {
  for (let i = 0; i < data.length; ++i) {
    if (data[i].type === "test1" && data[i].name === name) {
      return data[i];
    }
  }
}
//Shorthand
filteredData = data.find(
  (data) => data.type === "test1" && data.name === "fgh",
);
console.log(filteredData); // { type: 'test1', name: 'fgh' }
  • indexOf 的按位操作简化
//longhand
if (arr.indexOf(item) > -1) {
  // item found
}
if (arr.indexOf(item) === -1) {
  // item not found
}

//shorthand
if (~arr.indexOf(item)) {
  // item found
}
if (!~arr.indexOf(item)) {
  // item not found
}
if (arr.includes(item)) {
  // 如果找到项目,则为 true
}