都2023年了,JavaScript ES6后的新(lao)特性,你用起来了吗?

前言

JavaScript ES6 指的是 ECMAScript 6,它是 JavaScript 语言第六版的规范。ES6 包含了很多新特性和语法糖,涵盖了从 ES6 开始至今所增加的所有特性。

因此,ES6 新特性是指从 ES6 开始新增到当前时刻所有的新特性,包括但不限于 let 和 const、箭头函数、模板字符串、解构赋值、默认参数、Rest 和 Spread 操作符、Promise 等。这些新特性使得开发人员能够更加方便地编写复杂的应用程序,并且让代码更加简洁易读。

本文整理了一些开发中常用的新特性进行介绍。

1. let 和 const 声明变量

ES6 引入了 letconst 关键字,用于声明变量。与 var 不同,letconst 声明的变量都有块级作用域,且不能被重复声明。注意:const 声明必须立刻赋值。

let x = 10;
const PI = 3.14;
if (true) {
  let x = 20; // 不影响外部 x 的值
  const PI = 3.1416; // 不影响外部 PI 的值
}
console.log(x); // 10
console.log(PI); // 3.14

2. 解构赋值

解构赋值是一种通过数组或对象模式来提取值并对变量进行赋值的语法,非常方便实用。可以通过以下方式将一个对象中的元素赋值给新变量。

const person = {
  name: 'Tom',
  age: 18,
  gender: 'male'
}
const { name, age, gender } = person;
console.log(name); // "Tom"

3. 箭头函数

箭头函数是一种更加节省代码、更加易读和理解的函数表达式,它使用箭头符号 => 来代替传统函数的语法格式。箭头函数通常只在需要一个回调函数,特别是与数组和对象方法一起使用时显得最有用。

// 传统函数
function add(x, y) {
  return x + y;
}

// 箭头函数
const add = (x, y) => x + y;

箭头函数也可以简化回调函数的书写。

const numbers = [1, 2, 3, 4, 5];
const even = numbers.filter(num => num % 2 === 0);
console.log(even); // [2, 4]

4. 模板字符串

模板字符串使得字符串拼接更为方便。它使用反引号 `` 包围,并使用 ${} 来插入变量或运算表达式。

const name = 'Tom';
console.log(`My name is ${name}.`); // My name is Tom.

模板字符串也可跨行。

const html = `
<div>
  <h1>Hello World!</h1>
</div>
`;

5. 默认参数

默认参数可以在函数定义时为参数指定默认值,当调用函数时没有传入此参数,则会使用参数的默认值。

function sayHello(name = 'world') {
  console.log(`Hello, ${name}!`);
}
sayHello(); // "Hello, world!"
sayHello('Tom'); // "Hello, Tom!"

6. Rest (剩余)和 Spread(展开)操作符

Rest 和 Spread 操作符都使用 ... 语法,但有不同的作用。

  • Rest 参数用于接收剩余的数组元素,以数组形式存储
function sum(first, ...others) {
  let total = first;
  for (let i = 0; i < others.length; i++) {
    total += others[i];
  }
  return total;
}
console.log(sum(1, 2, 3, 4, 5)); // 15
  • Spread 操作符则用于展开数组,以逗号分隔的形式提供多个值。它可以在函数调用、数组、对象、Map 和 Set 等地方使用
// 数组拼接
const arr1 = [1, 2, 3];
const arr2 = [4, 5];
const arr3 = [...arr1, ...arr2];
console.log(arr3); // [1, 2, 3, 4, 5]

// 函数调用
const numbers = [1, 2, 3, 4, 5];
console.log(Math.max(...numbers)); // 5

// 创建新对象
const obj1 = { foo: 'bar', x: 42 };
const obj2 = { foo: 'baz', y: 13 };
const obj3 = { ...obj1, ...obj2 };
console.log(obj3); // {foo: "baz", x: 42, y: 13}

7. Promise

Promise 是一种处理异步操作的机制,它可以让我们更好地控制异步代码流程。

function fetchData(url) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.onload = () => {
      if (xhr.status === 200) {
        resolve(xhr.response);
      } else {
        reject(new Error(`Request failed with status code ${xhr.status}`));
      }
    };
    xhr.send();
  });
}

fetchData('https://jsonplaceholder.typicode.com/users')
  .then(data => console.log(data))
  .catch(error => console.error(error));

在以上示例中,我们创建了一个 Promise 并使用 XHR 发送了 AJAX 请求。如果请求成功,就用 resolve 方法返回结果,否则用 reject 方法返回错误信息。最后,使用 then 和 catch 方法来处理 Promise 的结果和错误。

8. await

await 关键字只能在 async 函数中使用,用于等待 Promise 对象的执行结果。

当 async 函数中的某个表达式使用了 await 关键字时,它会等待这个 Promise 对象的状态发生变化,当 Promise 对象进入 fulfilled 状态时,将把其 resolved 值作为该表达式的运算结果,并继续执行 async 函数中后续的代码。

async function foo() {
  try {
    const result = await someAsyncOperation();
    // result 是异步操作的返回值
  } catch(err) {
    // 错误处理
  }
}

上述示例中,await 等待 someAsyncOperation() 执行完毕,并将其 resolved 的值赋给变量 result,接着执行后续的代码。

需要注意的是,await 只能在 async 函数中使用,并且只能放在 Promise 对象前面。如果我们需要等待多个 Promise 对象,可以使用 Promise.all() 方法。

async function foo() {
  try {
    const [result1, result2] = await Promise.all([promise1, promise2]);
    // 等待 promise1 和 promise2 均完成,并将它们的 resolved 值分别赋值给 result1 和 result2
  } catch(err) {
    // 错误处理
  }
}

猜你喜欢

转载自blog.csdn.net/weixin_42373175/article/details/131321934