js快捷实现语句
JavaScript 快捷实现语句
箭头函数
箭头函数提供简洁的函数定义方式,适合单行操作。
const add = (a, b) => a + b;
const square = x => x * x;
模板字符串
使用反引号(`)嵌入变量或表达式,避免字符串拼接。
const name = 'Alice';
console.log(`Hello, ${name}!`);
解构赋值
快速提取对象或数组中的值到变量。
const user = { id: 1, name: 'Bob' };
const { id, name } = user;
const arr = [10, 20];
const [first, second] = arr;
扩展运算符
合并数组或对象时简化操作。
const arr1 = [1, 2];
const arr2 = [...arr1, 3]; // [1, 2, 3]
const obj1 = { a: 1 };
const obj2 = { ...obj1, b: 2 }; // { a: 1, b: 2 }
可选链(Optional Chaining)
避免深层属性访问时的报错。
const user = { address: { city: 'New York' } };
const city = user?.address?.city; // 'New York'
const zip = user?.address?.zip; // undefined
空值合并运算符(??)
提供默认值仅当左侧为 null 或 undefined 时生效。
const input = null;
const value = input ?? 'default'; // 'default'
数组方法链式调用
结合 map、filter、reduce 快速处理数据。
const numbers = [1, 2, 3];
const doubledEvens = numbers
.filter(n => n % 2 === 0)
.map(n => n * 2);
逻辑运算符短路赋值
利用 && 或 || 简化条件赋值。
const isAdmin = true;
const access = isAdmin && 'Full Access'; // 'Full Access'
const defaultValue = null || 'fallback'; // 'fallback'
立即执行函数(IIFE)
快速创建独立作用域。
(() => {
console.log('IIFE executed');
})();
对象属性简写
属性名与变量名相同时可省略值。
const age = 30;
const person = { age }; // { age: 30 }
