实际项目开发中的js小技巧

2023-09-27  本文已影响0人  zkzhengmeng

1.多个条件 if 语句简写

//常规写法
if (name === "abc" || name === "def" || name === "ghi" || name === "jkl") {
  //执行的语句
}

// 简写
if (["abc", "def", "ghi", "jkl"].includes(name)) {
  //执行的语句
}

2.简化 if...else 条件表达式

// 原式
let  test: boolean;
if (x > 100) {
  test = true;
} else {
  test = false;
}

// 运用三目运算符简写
let test = x > 100? true : false;
console.log(test);

3.标准JSON的深拷贝

var a = {
a: 1,
b: { c: 1, d: 2 }
}
var b=JSON.parse(JSON.stringify(a))
console.log(b)

4.数组去重

let  arr1 = [1, "1", 2, 1, 1, 3]
arr1  = [...new Set(arr1)]

5.打乱数组顺序

let  list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
list.sort(() => {return Math.random() - 0.5;});

6.从数组中过滤出虚假值(注意会过滤掉0)

Falsy值喜欢0,undefined,null,false,"",''可以很容易地通过以下方法省略
const array = [3, 0, 6, 7, '', false]; 
array.filter(Boolean); // 输出 (3) [3, 6, 7]
上一篇 下一篇

猜你喜欢

热点阅读