跳至主要內容

JS代码优雅指南

zfh大约 2 分钟约 628 字...

  1. 使用箭头函数简化函数定义
function add(a,b){
  return a+b
}
// 箭头函数
const add = (a,b)=>a+b
  1. 使用解构赋值简化变量声明
// 传统变量声明
const firstName=person.firstName
const lastName=person.lastName
// 解构赋值
const {firstName,lastName} = person
  1. 使用模板字面量进行字符串的拼接
// 传统字符串拼接
const greeting="hello,"+name+'!'
// 模板字面量拼接
const greeting=`hello,${name}!`
  1. 使用展开运算符进行数组和对象操作
// 浅拷贝
const combined=[...arr1,...arr2]

const clone = {...original}
  1. 使用数组的高阶方法简化循环和数据操作
// 遍历数组并返回新数组
const doubled = numbers.map(num => num * 2);
// 过滤数组
const evens = numbers.filter(num => num % 2 === 0);
  1. 使用条件运算符简化条件判断
// 传统条件判断
let message;
if (isSuccess) {
 message = 'Operation successful';
} else {
 message = 'Operation failed';
}
// 条件运算符简化
const message = isSuccess ? 'Operation successful' : 'Operation failed';
  1. 使用对象解构和默认参数简化函数参数
// 传统参数设置默认值
function greet(name) {
 const finalName = name || 'Guest';
 console.log(`Hello, ${finalName}!`);
 }
  
 // 对象解构和默认参数简化
 function greet({ name = 'Guest' }) {
 console.log(`Hello, ${name}!`);
 }
  1. 使用函数式编程概念如纯函数和函数组合
// 纯函数
function add(a, b) {
 return a + b;
 }
  
 // 函数组合
 const multiplyByTwo = value => value * 2;
 const addFive = value => value + 5;
 const result = addFive(multiplyByTwo(3));
  1. 使用对象字面量简化对象的创建和定义
// 传统对象创建
const person = {
 firstName: 'John',
 lastName: 'Doe',
 age: 30,
 };
  
 // 对象字面量简化
 const firstName = 'John';
 const lastName = 'Doe';
 const age = 30;
 const person = { firstName, lastName, age };
  1. 使用适当的命名和注释来提高代码可读性
// 不好的
const x = 10; // 设置x的值为10
function a(b) {
 return b * 2; // 返回b的两倍
}
// 好的
const speed = 10; // 设置速度为10
function double(value) {
 return value * 2; // 返回输入值的两倍
  1. 复杂逻辑判断使用对象或Map写法

if...else

let txt = '';
if (status == 1) {
 txt = "成功";
} else if (status == 2) {
 txt = "失败";
} else if (status == 3) {
 txt = "进行中";
} else {
 txt = "未开始";
}

或者使用switch case

let txt = '';
switch (status) {
 case 1:
 txt = "成功";
 break;
 case 2:
 txt = "成功";
 break;
 case 3:
 txt = "进行中";
 break;
 default:
 txt = "未开始";
}

都不怎么优雅,如果使用对象或者Map:

const statusMap = {
 1: "成功",
 2: "失败",
 3: "进行中",
 4: "未开始"
}
//调用直接 statusMapp[status]
const actions = new Map([
 [1, "成功"],
 [2, "失败"],
 [3, "进行中"],
 [4, "未开始"]
])
// 调用直接 actions.get(status)
上次编辑于:
本站勉强运行 小时
本站总访问量
網站計數器