返回

ES6变量声明和解构赋值,现代JavaScript语法入门

前端

ES6变量声明

在ES6中,可以使用letconst 来声明变量。let 声明的变量可以重新赋值,而const 声明的变量则不能重新赋值。这使得代码更加清晰、易于维护。

例如:

// 使用let声明变量
let name = "John";
name = "Mary";

// 使用const声明变量
const PI = 3.14;
// PI = 3.15; // 会报错

TDZ(临时死区)

letconst 变量声明都会创建临时死区。在临时死区内,变量名不能被引用,否则会报错。临时死区从变量声明开始,一直持续到变量声明所在块的结束。

例如:

{
  let name = "John";
  console.log(name); // "John"

  // 在这里,name是临时死区,不能被引用
  console.log(name); // ReferenceError: name is not defined
}

框架简图:

+----------------------------------------------------------+
| let name = "John";                                        |
|                                                          |
| // 在这里,name是临时死区,不能被引用                     |
| console.log(name); // ReferenceError: name is not defined |
+----------------------------------------------------------+

解构赋值

解构赋值是一种新的赋值语法,可以将数组或对象的元素赋值给多个变量。这使得代码更加简洁、易于阅读。

例如:

// 数组解构赋值
const [name, age] = ["John", 30];

console.log(name); // "John"
console.log(age); // 30

// 对象解构赋值
const { name, age } = { name: "John", age: 30 };

console.log(name); // "John"
console.log(age); // 30

默认值

在ES6中,可以为变量声明指定默认值。如果变量在声明时没有被赋值,则使用默认值。

例如:

let name = "John";
let age; // 默认值为undefined

console.log(name); // "John"
console.log(age); // undefined

// 为age指定默认值
let age = 30;

console.log(name); // "John"
console.log(age); // 30

对象结构

对象结构是一种新的语法,可以将对象中的属性提取出来,并赋值给多个变量。这使得代码更加简洁、易于阅读。

例如:

const person = {
  name: "John",
  age: 30,
  city: "New York"
};

// 使用对象结构提取属性
const { name, age, city } = person;

console.log(name); // "John"
console.log(age); // 30
console.log(city); // "New York"

JSON

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式。它基于JavaScript对象语法,可以表示各种数据结构,包括数组、对象、数字、字符串和布尔值。

例如:

const person = {
  name: "John",
  age: 30,
  city: "New York"
};

// 将对象转换为JSON字符串
const json = JSON.stringify(person);

console.log(json); // "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}"

// 将JSON字符串转换为对象
const person = JSON.parse(json);

console.log(person.name); // "John"
console.log(person.age); // 30
console.log(person.city); // "New York"

箭头函数

箭头函数是一种新的函数语法,可以简化函数的编写。箭头函数没有自己的this ,并且不能使用arguments 对象。

例如:

// 普通函数
function add(a, b) {
  return a + b;
}

// 箭头函数
const add = (a, b) => a + b;

console.log(add(1, 2)); // 3

结语

ES6的变量声明和解构赋值是现代JavaScript语法的重要组成部分。这些新特性使JavaScript更加简洁、易读和高效。如果您想编写高质量的JavaScript代码,那么掌握这些新特性是必不可少的。