技术 · 思考 · 实践 · 成长

首页/JavaScript/正文

JavaScript ES6+ 常用新特性:解构、展开、箭头函数与模块

JavaScript1 次阅读

ES6+ 是现代 JS 的标配语法。本文是新特性速查手册(深入见各专篇),结尾附工具函数库小案例。

一、变量与函数

let a = 1; const b = 2;                  // 块级作用域
const fn = (x) => x * 2;                 // 箭头函数
function greet(name = '游客') {}          // 默认参数
function sum(...nums) {}                 // 剩余参数
const add = (a, b) => ({ result: a + b }); // 返回对象加括号

二、解构与展开

const { name, age = 18 } = obj;          // 对象解构 + 默认值
const [first, second] = arr;             // 数组解构
const copy = { ...obj, age: 21 };        // 展开合并
const arr2 = [...arr1, 4];               // 数组合并
[a, b] = [b, a];                          // 变量交换

三、模板字符串与新 API

const msg = `你好 ${name},今年 ${age} 岁`;
// 字符串新方法
'abc'.includes('b'); 'abc'.padStart(5, '0'); 'abc'.at(-1);
// 数组新方法
Array.from('abc'); Array.of(1, 2); arr.find(x => x > 1); arr.flat(2); arr.at(-1);
// 对象新方法
Object.assign({}, obj); Object.entries(obj); Object.fromEntries([['a',1]]);

四、可选链与空值合并

user?.addr?.city             // 链上任何一环 undefined 都不报错
arr?.[0]                     // 数组安全访问
fn?.()                       // 函数安全调用
const v = input ?? '默认';    // 只有 null/undefined 取默认(比 || 准)
obj.x ??= 10;                // 逻辑赋值(空才赋)

五、Map 与 Set

const map = new Map();
map.set('a', 1).set('b', 2);
map.get('a'); map.has('a'); map.size;
for (const [k, v] of map) {}            // 任何类型做键、保插入序

const set = new Set([1, 2, 2, 3]);       // 自动去重
set.add(4); set.has(1); [...set];        // Set 转数组去重:[...new Set(arr)]

六、模块(ES Module)

// math.js
export const PI = 3.14;
export function add(a, b) { return a + b; }
export default class Calc {}             // 默认导出

// main.js
import Calc, { PI, add } from './math.js';
import * as math from './math.js';      // 整体导入

七、小案例:现代工具函数库

// utils.js —— ES6+ 语法大集合
export const isEmpty = (v) =>
    v == null || v === '' ||
    (Array.isArray(v) && v.length === 0) ||
    (typeof v === 'object' && Object.keys(v).length === 0);

export const unique = (arr) => [...new Set(arr)];

export const groupBy = (arr, keyFn) =>
    arr.reduce((acc, item) => {
        (acc[keyFn(item)] ??= []).push(item);
        return acc;
    }, {});

export const pick = (obj, keys) =>
    Object.fromEntries(keys.filter(k => k in obj).map(k => [k, obj[k]]));

export const sleep = (ms) => new Promise(r => setTimeout(r, ms));

// main.js
import { unique, groupBy, pick } from './utils.js';

const users = [
    { name: 'Tom', dept: 'A' },
    { name: 'Jerry', dept: 'B' },
    { name: 'Spike', dept: 'A' },
];
console.log(groupBy(users, u => u.dept));
console.log(unique([1, 1, 2]));
console.log(pick(users[0], ['name']));
// sleep(1000).then(() => console.log('1秒后'));

六个函数用尽 ??=/Object.fromEntries/Map 思维/Promise —— 现代 JS 写法的浓缩示范。

八、总结

let/const、箭头、解构展开、模板字符串是日常四件;?. 和 ?? 防空;Set 去重 Map 映射;模块 export/import;新 API 优先于手写循环。

无才无以立足,不苦不能成才。

评论交流

0 条评论 · 支持多级回复
验证码
暂无评论,来说说你的想法吧

相关文章

继续阅读