1. 模板字符串
在 ES5 中要么是 单引号包裹要么是双引号包裹 而 ES6 中推出的 模板字符串是 使用 ``
两者区别
- 反引号能够换行, 但是单引号双引号不行
- 内部如果书写的 有 ${} 然后在内部可以识别出变量
展开运算符 ...
在 ES6 推出了展开运算符 ...
能够展开数组 或者 对象
let arr = [1,2,3]
console.log(arr)/[1,2,3]
console.log(...arr) //1 2 3
//2.1 可以合并数组
let arr2 = [...arr,100,101,102]
console.log(arr2)//[1, 2, 3, 100, 101, 102]
//2.2函数传参
function fn(a, b, c) {
console.log('fn 函数的 形参: ', a, b, c)
}
fn(arr[0], arr[1], arr[2])//fn 函数的 形参: 1 2 3
fn(...arr)//fn 函数的 形参: 1 2 3
// 2.3 展开对象
let obj = {
a: 1,
b: 2
}
// console.log(...obj) 这个代码不符合语法规范
let obj2 = {
...obj,
c: 100,
d: 200
}
console.log(obj2)//{a: 1, b: 2, c: 100, d: 200}
//... 属于浅拷贝
let b1 = {a:[1,2,3],b:4}
let b2 = {...b1}
b2.a.push(15)
console.log(b1,b2)//{a:[1,2,3,15],b:4}
//重复的会被覆盖
let z = {a:[1,2,3],b:4}
let o = {c:10,b:4}
let n = {...z,...o}
console.log(n)//{a:[1,2,3],b:4,c:10}
对象的简写语法
ES6 允许在大括号里面,直接写入变量和函数,作为对象的属性和方法。这样的书写更加简洁。
属性简写
const foo = 'bar';
const baz = {foo};
baz // {foo: "bar"}
// 等同于 const baz = {foo: foo};
//变量foo直接写在大括号里面。这时,属性名就是变量名, 属性值就是变量值。下面是另一个例子。
function f(x, y) {
return {x, y};
}
// 等同于
function f(x, y) {
return {x: x, y: y};
}
f(1, 2)
// Object {x: 1, y: 2}
方法简写
const o = {
method() {
return "Hello!";
}
};
//等同于
const o = {
method:function(){
return "Hello"
}
}