JS的传统写法 vs 简写形式
一、条件判断与逻辑操作
-
三元运算符简化条件判断
// 传统写法 let result; if (someCondition) {result = 'yes'; } else {result = 'no'; }// 简写方式 const result = someCondition ? 'yes' : 'no';
-
短路求值
// 传统写法 if (condition) {doSomething(); }// 简写方式 condition && doSomething();
-
空值合并运算符
// 传统写法 const name = user.name !== null && user.name !== undefined ? user.name : 'default';// 简写方式 const name = user.name ?? 'default';
-
可选链操作符
// 传统写法 const street = user && user.address && user.address.street;// 简写方式 const street = user?.address?.street;
-
逻辑或和逻辑与赋值简写
// 传统写法 if (!value) value = defaultValue;// 简写方式 value ||= defaultValue; // 仅在 value 为假值时赋值// 类似逻辑 value &&= newValue; // 仅在 value 为真值时赋值
二、数组操作
-
数组去重
// 传统写法 function unique(arr) {return arr.filter((item, index) => arr.indexOf(item) === index); }// 简写方式 const unique = arr => [...new Set(arr)];
-
快速取整
// 传统写法 const floor = Math.floor(4.9);// 简写方式 const floor = ~~4.9;
-
数组展开(Spread Operator)
// 传统写法 const array1 = [1, 2, 3]; const array2 = [4, 5, 6]; const combined = array1.concat(array2);// 简写方式 const combined = [...array1, ...array2];
-
使用
reduce
进行累加操作// 传统写法 const numbers = [1, 2, 3, 4, 5]; let sum = 0; for (let i = 0; i < numbers.length; i++) {sum += numbers[i]; }// 简写方式 const sum = numbers.reduce((acc, num) => acc + num, 0);
-
使用
find
查找数组中的第一个匹配项// 传统写法 const users = [{ id: 1 }, { id: 2 }, { id: 3 }]; let foundUser = null; for (let i = 0; i < users.length; i++) {if (users[i].id === 2) {foundUser = users[i];break;} }// 简写方式 const foundUser = users.find(user => user.id === 2);
-
使用
map
创建新数组// 传统写法 const numbers = [1, 2, 3]; let doubledNumbers = []; for (let i = 0; i < numbers.length; i++) {doubledNumbers.push(numbers[i] * 2); }// 简写方式 const doubledNumbers = numbers.map(num => num * 2);
-
使用
filter
过滤数组元素// 传统写法 const numbers = [1, 2, 3, 4, 5]; let evenNumbers = []; for (let i = 0; i < numbers.length; i++) {if (numbers[i] % 2 === 0) {evenNumbers.push(numbers[i]);} }// 简写方式 const evenNumbers = numbers.filter(num => num % 2 === 0);
-
使用
every
检查所有元素是否满足条件// 传统写法 const numbers = [1, 2, 3, 4, 5]; let allEven = true; for (let i = 0; i < numbers.length; i++) {if (numbers[i] % 2 !== 0) {allEven = false;break;} }// 简写方式 const allEven = numbers.every(num => num % 2 === 0);
-
使用
some
检查是否有任意元素满足条件// 传统写法 const numbers = [1, 2, 3, 4, 5]; let hasEven = false; for (let i = 0; i < numbers.length; i++) {if (numbers[i] % 2 === 0) {hasEven = true;break;} }// 简写方式 const hasEven = numbers.some(num => num % 2 === 0);
-
数组扁平化
// 传统写法 const flattened = arr.reduce((acc, val) => acc.concat(val), []);// 简写方式 const flattened = arr.flat(); // 或指定深度:arr.flat(2)
-
快速生成连续数字数组
// 传统写法 const range = []; for (let i = 0; i < 5; i++) range.push(i);// 简写方式 const range = [...Array(5).keys()]; // [0, 1, 2, 3, 4]
-
使用
Boolean
过滤假值// 传统写法 const filtered = arr.filter(item => !!item);// 简写方式 const filtered = arr.filter(Boolean); // 过滤掉 null、undefined、0、'' 等
-
快速克隆数组
// 传统写法 const copyArr = arr.slice();// 简写方式 const copyArr = [...arr];
-
使用
Array.includes
替代多条件||
// 传统写法 if (value === 'a' || value === 'b' || value === 'c') {}// 简写方式 if (['a', 'b', 'c'].includes(value)) {}
-
使用
Array.at
访问数组末尾元素const arr = [1, 2, 3];// 传统写法 const last = arr[arr.length - 1]; // 3// 简写方式 const last = arr.at(-1); // 3 (也支持负数索引)
-
合并多个数组并去重
const mergedUnique = [...new Set([...arr1, ...arr2])];
-
获取数组最大/最小值
const max = Math.max(...arr); const min = Math.min(...arr);
-
使用
Array.from
快速生成序列// 生成 0-4 的数组 const arr = Array.from({ length: 5 }, (_, i) => i); // [0, 1, 2, 3, 4]
三、对象操作
-
合并对象
// 传统写法 const merged = Object.assign({}, obj1, obj2);// 简写方式 const merged = {...obj1, ...obj2};
-
对象属性简写
// 传统写法 const name = 'Alice'; const age = 25; const user = {name: name,age: age };// 简写方式 const user = { name, age }; // 当 key 和 value 名称一致时
-
动态对象属性
// 传统写法 const obj = {}; obj[dynamic + 'name'] = value;// 简写方式 const obj = {[`${dynamic}name`]: value };
-
快速克隆对象
// 传统写法 const copyObj = Object.assign({}, obj);// 简写方式 const copyObj = { ...obj };
-
深拷贝一个对象(非函数/循环引用)
const deepCopy = obj => JSON.parse(JSON.stringify(obj));
-
使用
Object.entries
或Object.values
快速遍历对象const obj = { a: 1, b: 2 };// 遍历键值对 Object.entries(obj).forEach(([key, value]) => console.log(key, value));// 直接获取值 const values = Object.values(obj); // [1, 2]
-
判断是否为空对象
const isEmpty = obj => Object.keys(obj).length === 0;
四、字符串操作
-
字符串转数字
// 传统写法 const num = parseInt('456', 10); const floatNum = parseFloat('456.78');// 简写方式 const num = +'456'; // 转为整数或浮点数 const num2 = Number('456');
-
模板字符串
// 传统写法 const name = "John"; const greeting = "Hello, " + name + "!";// 简写方式 const greeting = `Hello, ${name}!`;
-
使用
String.repeat
快速重复字符串// 传统写法 let str = ''; for (let i = 0; i < 3; i++) str += 'ha';// 简写方式 const str = 'ha'.repeat(3); // 'hahaha'
-
使用
replaceAll
替换所有匹配字符串// 传统写法 const str = 'a-b-c'.replace(/-/g, '_'); // 'a_b_c'// 简写方式 const str = 'a-b-c'.replaceAll('-', '_'); // 'a_b_c'
五、函数与参数
-
默认参数值
// 传统写法 function greet(name) {name = name || 'Guest';console.log(`Hello ${name}`); }// 简写方式 const greet = (name = 'Guest') => console.log(`Hello ${name}`);
-
默认参数值与解构赋值结合
// 传统写法 function drawRectangle(width, height) {width = width || 50;height = height || 50;console.log(`Width: ${width}, Height: ${height}`); }// 简写方式 const drawRectangle = ({ width = 50, height = 50 } = {}) => {console.log(`Width: ${width}, Height: ${height}`); };
六、变量操作
-
解构赋值
// 传统写法 const first = arr[0]; const second = arr[1];// 简写方式 const [first, second] = arr;
-
交换变量值
// 传统写法 let a = 1, b = 2; let temp = a; a = b; b = temp;// 简写方式(使用解构) let a = 1, b = 2; [a, b] = [b, a]; // 一行交换两个变量
七、异步操作
-
使用
Promise.all
并行处理异步任务// 传统写法:依次等待 const res1 = await fetch(url1); const res2 = await fetch(url2);// 简写方式:并行执行 const [res1, res2] = await Promise.all([fetch(url1), fetch(url2)]);
八、类型转换
-
使用
!!
快速转换为布尔值// 传统写法 const isTruthy = Boolean(value);// 简写方式 const isTruthy = !!value; // 双感叹号强制转换
九、大数字处理
-
使用
BigInt
处理大数字// 传统写法(可能丢失精度) const bigNum = 9007199254740991;// 简写方式 const bigNum = 9007199254740991n; // 后缀加 'n'
十、日期/数字格式化
-
使用
Intl
简化日期/数字格式化// 格式化数字 const num = 123456.789; console.log(new Intl.NumberFormat('en-US').format(num)); // "123,456.789"// 格式化日期 const date = new Date(); console.log(new Intl.DateTimeFormat('zh-CN').format(date)); // "2023/7/20"
十一、DOM 操作
-
将类数组转换为数组(如 arguments 或 NodeList)
const arr = Array.from(document.querySelectorAll('div'));