模板字符串(Template Strings)
模板字符串是ES6引入的一种新的字符串表示法,允许嵌入表达式和创建多行字符串。它们被反引号包围(` \),并且可以包含${expression}
作为占位符,用于从JavaScript表达式中获取值。
-
基本用法:
const name = "John"; const greeting = `Hello, ${name}!`; console.log(greeting); // 输出: Hello, John!
-
多行字符串:
const multiLine = `This is a string that spans across multiple lines.`; console.log(multiLine);
解构赋值(Destructuring Assignment)
解构赋值是ES6的一个语法特性,允许将数组或对象的属性解包到一系列变量中,这使得从数组或对象中提取数据变得更加简便。
-
数组解构:
const arr = [1, 2, 3]; const [a, b, c] = arr; console.log(a, b, c); // 输出: 1 2 3
-
对象解构:
const person = { name: "John", age: 30 }; const { name, age } = person; console.log(name, age); // 输出: John 30
-
函数参数解构:
function greet({ name, age }) { console.log(`Hello, ${name}. You are ${age} years old.`); } greet(person); // 输出: Hello, John. You are 30 years old.
默认参数(Default Parameters)
默认参数允许在函数定义时为参数指定默认值。如果调用函数时未提供参数,或者参数值为undefined
,则使用默认值。
-
基本用法:
function greet(name = "Guest") { console.log(`Hello, ${name}!`); } greet("John"); // 输出: Hello, John! greet(); // 输出: Hello, Guest!
-
与解构结合使用:
function createPerson({ name = "John Doe", age = 30 } = {}) { console.log(`Name: ${name}, Age: ${age}`); } createPerson({ name: "Alice", age: 25 }); // 输出: Name: Alice, Age: 25 createPerson(); // 输出: Name: John Doe, Age: 30
这些ES6特性极大地增强了JavaScript的表达能力,使得代码更加简洁、清晰,并提高了开发效率。