1.变量声明const和let
①let 和const都是块级作用域,并且都不会有变量提升
②const声明的变量都会被认为是常量,不能被修改,但如果被const修饰的是对象,对象中的属性值可以被修改
看一道简单的题目
var funcs = []
for (var i = 0; i < 5; i++) {
funcs.push(function() { console.log(i) })
}
funcs.forEach(function(func) {
func()
})
输出结果显而易见是输出五个5,但如果想输出0~9应该怎么做呢?看下ES5和ES6分别怎么做
// ES5告诉我们可以利用闭包解决这个问题 var funcs = []
for (var i = 0; i < 5; i++) {
funcs.push(
(function(value) {
return function() {
console.log(value)
}
})(i)
)
}
funcs.forEach(function(func) {
func()
})
//ES6中只需要使用let const funcs = []
for (let i = 0; i < 10; i++) {
funcs.push(function() {
console.log(i)
})
}
funcs.forEach(func => func())
2.模板字符串
第一个用途,基本的字符串格式化。将表达式嵌入字符串中进行拼接。用${}来界定
//ES5 var name = 'lili' console.log('hello' + name)
//es6 const name = 'lili' console.log(`hello ${name}`) //hello lili
第二个用途,在ES5时我们通过反斜杠(\)来做多行字符串拼接。ES6反引号(``)直接搞定。
// ES5 var msg = "Hi \
man!
" // ES6 const template = `<div>
<span>hello world</span>
</div>`
对于字符串ES6当然也提供了很多厉害也很有意思的方法
const str = 'hahay' console.log(str.includes('y')) // true const str = 'he' console.log(str.repeat(3)) // 'hehehe' const str = 'hello world!' console.log(str.startsWith('hello')) // true console.log(str.endsWith('!')) // true
3.函数
函数默认参数
//es5 function action(num) {
num = num || 200 return num
}
//es6 function action(num = 200) {
console.log(num)
}
箭头函数
//es6
[1,2,3].map(x => x + 1)
//es5
[1,2,3].map((function(x){
return x + 1
}).bind(this))
4.拓展的对象功能
键值对简写
//es5 function people(name, age) {
return {
name: name,
age: age
};
}
//es6 function people(name, age) {
return {
name,
age
};
}
//方法同样适用 //es5 const people = {
name: 'lux',
getName: function() {
console.log(this.name)
}
}
//es6 const people = {
name: 'lux',
getName () {
console.log(this.name)
}
}
浅拷贝Object.assign()
const objB = { address: 'beijing' }
const objC = {} // 这个为目标对象 const obj = Object.assign(objC, objB)
console.log(objB) // { address: 'beijing' } console.log(objC) // { address: 'beijing' } console.log(obj) // { address: 'beijing' } //obj为 objC的浅拷贝 //虽然assign被定义为浅拷贝,但是第一个参数传入{}可以达到深拷贝的效果 const objB = { address: 'beijing' }
const obj = Object.assign({}, objB)
console.log(objB) // { address: 'beijing' } console.log(obj) // { address: 'beijing' }
此时obj为objB的深拷贝
5.解构
var people = {
name: 'lux',
age: 20
}
//es5 var name = people.name
var age = people.age
//es6 const {name, age} = people
//数组同样适用 var arr = [1,2,3];
const {one, , three} = arr;
6.Spread Operator 展开运算符
//数组 const color = ['red', 'yellow']
const colorful = [...color, 'green', 'pink']
console.log(colorful) //[red, yellow, green, pink] //对象 const alp = { fist: 'a', second: 'b'}
const alphabets = { ...alp, third: 'c' }
console.log(alphabets) //{ "fist": "a", "second": "b", "third": "c"