JavaScript 实用技巧:10 个让你代码更优雅的方法

导读:为什么要学这些技巧?

写代码不难,难的是写出优雅、易维护的代码。今天分享 10 个 JavaScript 实用技巧,都是实际项目中总结出来的经验。

学会这些,你的代码质量会提升一个档次。

技巧 1:使用解构赋值简化代码

Before(传统写法)

const user = { name: '张三', age: 25, city: '北京' };
const name = user.name;
const age = user.age;
const city = user.city;

After(解构写法)

const user = { name: '张三', age: 25, city: '北京' };
const { name, age, city } = user;

效果

代码减少 75%,可读性更好。

进阶用法

// 数组解构
const [first, second, ...rest] = [1, 2, 3, 4, 5];

// 对象解构 + 重命名
const { name: userName, age: userAge } = user;

// 默认值
const { name, country = '中国' } = user;

技巧 2:使用可选链操作符

Before(多层判断)

let street = user.address;
if (street) {
  street = street.street;
  if (street) {
    street = street.name;
  }
}

After(可选链)

const street = user?.address?.street?.name;

效果

代码减少 90%,避免”Cannot read property of undefined”错误。

技巧 3:使用空值合并运算符

Before

const name = userName !== null && userName !== undefined 
  ? userName 
  : '默认用户';

After

const name = userName ?? '默认用户';

与||的区别

// || 会把 0、''、false 当成假值
const count = 0 || 10;  // 10(错误)

// ?? 只判断 null 和 undefined
const count = 0 ?? 10;  // 0(正确)

技巧 4:使用 Array 方法替代循环

Before(for 循环)

const numbers = [1, 2, 3, 4, 5];
const doubled = [];
for (let i = 0; i < numbers.length; i++) {
  doubled.push(numbers[i] * 2);
}

After(map 方法)

const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(n => n * 2);

常用方法对比

// map - 转换数组
const names = users.map(u => u.name);

// filter - 过滤数组
const adults = users.filter(u => u.age >= 18);

// reduce - 汇总数组
const total = prices.reduce((sum, p) => sum + p, 0);

// find - 查找元素
const user = users.find(u => u.id === 1);

// some - 至少一个满足条件
const hasAdult = users.some(u => u.age >= 18);

// every - 全部满足条件
const allAdults = users.every(u => u.age >= 18);

技巧 5:使用模板字符串

Before(字符串拼接)

const greeting = '你好,' + name + '!' + 
  '你今年' + age + '岁了。';

After(模板字符串)

const greeting = `你好,${name}!你今年${age}岁了。`;

多行字符串

// Before
const html = '
' + '

标题

' + '

内容

' + '
'; // After const html = `

标题

内容

`;

技巧 6:使用展开运算符

数组合并

// Before
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const merged = arr1.concat(arr2);

// After
const merged = [...arr1, ...arr2];

对象合并

const defaults = { theme: 'light', lang: 'zh' };
const userPrefs = { theme: 'dark' };
const config = { ...defaults, ...userPrefs };
// 结果:{ theme: 'dark', lang: 'zh' }

函数参数

function sum(...numbers) {
  return numbers.reduce((a, b) => a + b, 0);
}
sum(1, 2, 3, 4, 5);  // 15

技巧 7:使用箭头函数

Before

const numbers = [1, 2, 3];
const doubled = numbers.map(function(n) {
  return n * 2;
});

After

const numbers = [1, 2, 3];
const doubled = numbers.map(n => n * 2);

注意事项

// 箭头函数没有自己的 this
// 不要在对象方法中使用箭头函数
const obj = {
  name: '张三',
  // 错误
  greet: () => console.log(this.name),
  // 正确
  greet() { console.log(this.name); }
};

技巧 8:使用 Promise.all 并行处理

Before(串行)

async function fetchData() {
  const user = await fetchUser();
  const posts = await fetchPosts();
  const comments = await fetchComments();
  return { user, posts, comments };
}

After(并行)

async function fetchData() {
  const [user, posts, comments] = await Promise.all([
    fetchUser(),
    fetchPosts(),
    fetchComments()
  ]);
  return { user, posts, comments };
}

效果

如果每个请求耗时 1 秒,串行需要 3 秒,并行只需 1 秒。

技巧 9:使用 async/await 处理异步

Before(Promise 链)

fetchUser(userId)
  .then(user => fetchPosts(user.id))
  .then(posts => fetchComments(posts[0].id))
  .then(comments => console.log(comments))
  .catch(error => console.error(error));

After(async/await)

try {
  const user = await fetchUser(userId);
  const posts = await fetchPosts(user.id);
  const comments = await fetchComments(posts[0].id);
  console.log(comments);
} catch (error) {
  console.error(error);
}

效果

代码更像同步,易于理解和调试。

技巧 10:使用模块化组织代码

导出(export.js)

// 命名导出
export const PI = 3.14;
export function add(a, b) {
  return a + b;
}

// 默认导出
export default class Calculator {
  // ...
}

导入(import.js)

// 命名导入
import { PI, add } from './export.js';

// 默认导入
import Calculator from './export.js';

// 全部导入
import * as Math from './export.js';

实战建议

  1. 不要一次性全部用上 - 循序渐进,逐个掌握
  2. 看团队代码规范 - 保持一致性比用新特性更重要
  3. 注意浏览器兼容性 - 老项目可能需要 Babel 转译
  4. 性能优先 - 有些场景传统写法性能更好

总结

这些技巧都是实际项目中总结出来的,能帮你写出更优雅、更易维护的代码。

建议收藏这篇文章,写代码时拿出来参考。用多了就自然掌握了。

有问题欢迎评论区交流!


分类:编程/技术 | 关键词:JavaScript 技巧 | 阅读时间:约 15 分钟

© 版权声明

相关文章

没有相关内容!

暂无评论

none
暂无评论...