模板字符串
const student = {
name: "Wango",
age: 24,
}
// 普通字符串
const info1 = "My name is " + student.name + ", and I'm " + student.age + " years old";
// 模板字符串
const info2 = `My name is ${student.name}, and I'm ${student.age} years old`;
console.log(info1 === info2);
// true
模板字符串占位符${}内可以放置任意JS表达式,且不局限于一行
解构
对象的解构
const student = {
name: "Wango",
age: 24,
gender: "male",
}
// 对象解构,变量名必须与对象的属性名一致
let {name, age, gender} = student;
console.log(name === student.name);
// true
console.log(age === student.age);
// true
console.log(gender === student.gender);
// true
// 对象解构,显式指定要赋值的变量
let {name: myName, age: myAge, gender: myGender} = student;
console.log(myName === student.name);
// true
console.log(myAge === student.age);
// true
console.log(myGender === student.gender);
// true
数组的解构
const students = ["Wango", "Lily", "Jack", "Tom"];
// 数组元素的值按顺序赋值给指定变量
let [stu1, stu2, stu3, stu4] = students;
console.log(stu1 === students[0]);
// true
console.log(stu2 === students[1]);
// true
console.log(stu3 === students[2]);
// true
console.log(stu4 === students[3]);
// true
// 可以跳过特定的数组项
[stu1, , stu2, ,] = students;
console.log(stu1 === students[0]);
// true
console.log(stu2 === students[2]);
// true
// 可以捕获要追踪的项
let [first, ...remaining] = students
console.log(first === students[0]);
// true
console.log(remaining);
// ["Lily", "Jack", "Tom"]
// 字符串本质上也是数组,也可以用解构
const a = "Hello world!";
const [b, ...c] = a;
console.log(b);
// H
console.log(c);
// ["e", "l", "l", "o", " ", "w", "o", "r", "l", "d", "!"]
增强版对象字面量
// 原有对象字面量
const name = "Wango";
const student = {
// 在作用域内创建一个与变量同名的属性,
// 并将该变量的值赋给它
name: name,
// 定义一个方法
getName: function() {
return this.name;
}
};
// 创建一个动态生成的属性
student["newStudent" + name] = true;
// ES6增强版对象字面量
const newStudent = {
name, // 简写,直接将同名变量的值赋给属性
getName() { //直接方法名加括号,表明这是一个方法
return this.name;
},
// 动态属性名
["newStudent" + name]: true,
}