2023-12-11
// 传统函数定义
function add(a, b) {
return a + b;
}
// 箭头函数简化
const add = (a, b) => a + b;
// 传统变量声明
const firstName = person.firstName;
const lastName = person.lastName;
// 解构赋值简化
const { firstName, lastName } = person;
// 传统字符串拼接
const greeting = 'Hello, ' + name + '!';
// 模板字面量简化
const greeting = `Hello, ${name}!`;
// 遍历数组并返回新数组
const doubled = numbers.map(num => num * 2);
// 过滤数组
const evens = numbers.filter(num => num % 2 === 0);
// 传统条件判断
let message;
if (isSuccess) {
message = 'Operation successful';
} else {
message = 'Operation failed';
}
// 条件运算符简化
const message = isSuccess ? 'Operation successful' : 'Operation failed';
// 传统参数设置默认值
function greet(name) {
const finalName = name || 'Guest';
console.log(`Hello, ${finalName}!`);
}
// 对象解构和默认参数简化
function greet({ name = 'Guest' }) {
console.log(`Hello, ${name}!`);
}