每天一个小知识---ES6的新特性

83 阅读1分钟

ES6的新特性

1.let和const关键字。它们可以用来声明块级作用域的变量和常量,避免了使用var带来的一些问题。

// 使用var定义变量  
var x = 1;  
var y = 2;  
  
console.log(x); // 3  
console.log(y); // 3  
  
// 使用let定义变量  
let z = 3;  
const w = 4;  
  
console.log(z); // 3  
console.log(w); // ReferenceError: w is not defined

2.箭头函数。这是一种新的函数定义语法,它可以让我们更方便地编写函数,并且自动绑定this关键字。

// 传统函数写法  
function add(a, b) {  
  return a + b;  
}  
console.log(add(12)); // 3  
  
// 箭头函数写法  
const multiply = (a, b) => a * b;  
console.log(multiply(23)); // 6

3.模板字符串。这是一种新的字符串定义语法,它可以让我们更方便地拼接字符串,并且支持多行字符串和内嵌表达式。

let name = "John";  
let age = 30;  
let city = "New York";  
  
console.log(`My name is  $${name} and I'm  $${age} years old. I live in  $${city}.`); // My name is John and I'm 30 years old. I live in New York.

4.解构赋值。这是一种新的赋值语法,它可以让我们更方便地从对象或数组中提取值,并将其赋给变量。

const person = { name"Alice"age25 };  
const { name, age } = person;  
console.log(name); // Alice  
console.log(age); // 25

5. 扩展运算符。这是一种新的运算符,它可以让我们更方便地将数组或对象展开为多个参数或元素。

const arr1 = [123];  
const arr2 = [456];  
const arr3 = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]