在此列举一些前端开发中常用的JavaScript相关的高效小技巧

目录

1、数组去重

2、对象属性动态命名

3、短路运算设置默认值

4、快速深拷贝对象

5、数组快速清空

欢迎关注VX公众号:前端小知识营地


1、数组去重

const arr = [1, 2, 2, 3];
const unique = [...new Set(arr)];
console.log('unique', unique) // [1, 2, 3]

2、对象属性动态命名

const key = "name";
const obj = { [key]: "Alice" };
console.log('obj', obj); // { name: "Alice" }

3、短路运算设置默认值

const input = 'string';
const num = null;
const value = input || "default";
const count = num ?? 0; // 仅当 null/undefined 时用 0(空值合并)
console.log('value', value); // 'string'
console.log('count', count); // 0

4、快速深拷贝对象

const obj = { a: 1, b: { c: 2 } };
const copy = JSON.parse(JSON.stringify(obj)); // 注意:不适用函数/循环引用
console.log('copy', copy); // { a: 1, b: { c: 2 } }

5、数组快速清空

const arr = [1, 2, 3];
arr.length = 0; 
console.log('arr', arr); // []

欢迎关注VX公众号:前端小知识营地

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐