管理

(转载)20个JavaScript重点知识点(5)现代特性

Posted on 2025-06-02 09:47  lzhdim  阅读(10045)  评论(0)    收藏  举报
JavaScript的发展历程JavaScript早期版本主要用于简单的动态效果和表单验证,随着web技术的发展 ,ECMAScript 1发布,成为JavaScript的基础标准。然而,JavaScript的标准化过程并非一帆风顺,ECMAScript 4.0版草案因功能过于激进而未能通过,最终被放弃,取而代之的是更为保守的ECMAScript 3.1‌。直到2009年发布的ECMAScript 5引入了严格模式、JSON支持等新特性。2015年,ECMAScript 6(也称为ECMAScript 2015)引入了大量新特性,包括let和const关键字、箭头函数、模板字符串、解构赋值、Promise、模块系统等,大大增强了JavaScript的能力。此后,ECMAScript每年都会发布一个新版本,持续引入新功能和改进‌。本文主要针对JavaScript现代特性详解(ES6+)!

变量声明改进

1. let/const

// 块级作用域{  let a = 10  const B = 20  var c = 30}console.log(c) // 30console.log(a) // ReferenceErrorconsole.log(B) // ReferenceError
// const特殊说明const obj = { name: 'John' }obj.age = 30 // 允许修改属性obj = {}     // TypeError: 禁止重新赋值
// 暂时性死区(TDZ)console.log(x) // ReferenceErrorlet x = 5

2. 解构赋值

数组解构:

const [a, , b] = [1, 2, 3]console.log(a, b) // 1 3
// 默认值const [x=0, y=0] = [5]console.log(x, y) // 5 0
// 交换变量let m = 1, n = 2;[m, n] = [n, m]

对象解构:

const user = {   name: 'Alice',  age: 25,  address: {    city: 'New York'  }}
const {   name: userName,   age,   address: { city } } = user
console.log(userName, age, city) // Alice 25 New York
// 函数参数解构function greet({ name, age = 18 }) {  console.log(`Hello ${name}, age ${age}`)}

函数增强

1. 箭头函数

// 基本语法const sum = (a, b) => a + b
// 单参数简写const square = n => n * n
// 返回对象const createUser = (name) => ({ name })
// this绑定const counter = {  count: 0,  increment: function() {    setInterval(() => {      this.count++ // 正确绑定外层this    }, 1000)  }}

2. 参数处理

默认参数:

function createElement(type = 'div', classes = []) {  // ...}

剩余参数:

function sum(...numbers) {  return numbers.reduce((acc, curr) => acc + curr, 0)}
扩展运算符:
const arr1 = [1, 2]const arr2 = [...arr1, 3, 4] // [1,2,3,4]
const obj1 = { a: 1 }const obj2 = { ...obj1, b: 2 } // {a:1, b:2}

对象与类

1. 对象字面量增强

const name = 'Bob'const age = 30
const person = {  name,  // 属性简写  age,  // 方法简写  sayHi() {    console.log(`Hi, I'm ${this.name}`)  },  // 计算属性名  [Symbol.iterator]() { /*...*/ }}

2. Class语法

class Animal {  constructor(name) {    this.name = name  }
  speak() {    console.log(`${this.name} makes a noise`)  }
  static create(name) {    return new Animal(name)  }}
class Dog extends Animal {  #secret = 'bone' // 私有字段
  speak() {    super.speak()    console.log('Woof!')  }
  get secret() {    return this.#secret  }}

异步处理

function fetchData(url) {  return new Promise((resolve, reject) => {    fetch(url)      .then(response => {        if (!response.ok) throw new Error('Network error')        return response.json()      })      .then(data => resolve(data))      .catch(error => reject(error))  })}
// Promise链fetchData('/api/users')  .then(users => {    console.log('Total users:', users.length)    return fetchData('/api/posts')  })  .then(posts => {    console.log('Latest post:', posts[0])  })  .catch(error => {    console.error('Error:', error)  })

2. async/await

async function loadData() {  try {    const users = await fetchData('/api/users')    const posts = await fetchData('/api/posts')    return { users, posts }  } catch (error) {    console.error('Failed to load:', error)    throw error  }}
// 并行请求async function parallelRequests() {  const [user, posts] = await Promise.all([    fetchData('/api/user/1'),    fetchData('/api/posts')  ])  return { user, posts }}

模块系统

1. ES Modules

// math.jsexport const PI = 3.14159
export function sum(...nums) {  return nums.reduce((a, b) => a + b, 0)}
export default class Calculator {  // ...}
// app.jsimport Calc, { PI, sum } from './math.js'

2. 动态导入

async function loadModule() {  const module = await import('./module.js')  module.doSomething()}

最新特性(ES2020+)

1. 可选链操作符

const user = {  profile: {    name: 'Alice'  }}
console.log(user?.profile?.name) // Aliceconsole.log(user?.address?.city) // undefined

2. 空值合并运算符

const config = {  timeout: 0}
const timeout = config.timeout ?? 3000 // 0const port = config.port ?? 8080       // 8080

3. Promise.allSettled

const promises = [  Promise.resolve(1),  Promise.reject('Error'),  Promise.resolve(3)]
Promise.allSettled(promises).then(results => {  results.forEach(result => {    if (result.status === 'fulfilled') {      console.log('Value:', result.value)    } else {      console.log('Reason:', result.reason)    }  })})

实用新方法

1. 数组方法

// flat/flatMapconst arr = [1, [2, [3]]]console.log(arr.flat(2)) // [1, 2, 3]
const sentences = ["Hello world", "Good morning"]const words = sentences.flatMap(s => s.split(' '))// ["Hello", "world", "Good", "morning"]
// Array.fromconst set = new Set([1, 2, 3])const array = Array.from(set) // [1,2,3]

2. 对象方法

const obj = { a: 1, b: 2 }
// Object.entriesfor (const [key, value] of Object.entries(obj)) {  console.log(key, value)}
// Object.fromEntriesconst entries = [['a', 1], ['b', 2]]const newObj = Object.fromEntries(entries)

总结

  1. 1.优先使用const声明变量,需要重新赋值时使用let

  2. 2.使用箭头函数保持this上下文一致性

  3. 3.合理使用解构简化代码结构

  4. 4.使用Class进行面向对象编程

  5. 5.异步处理优先使用async/await

  6. 6.使用ES Module组织模块化代码

  7. 7.利用现代数组/对象方法简化数据处理

Copyright © 2000-2022 Lzhdim Technology Software All Rights Reserved