let/sonst
- let:定以后可以修改的变量
- const:定以后不能再修改的常量
//JS
var i = 10;
i = 100;
//ES6
let i = 10;
i = 100; //true
const j =20;
j = 200; //flase
多行字符串/模板变量
//JS
var name = 'zhangsan', age = 20, html = '';
html += '<div>';
html += '<p>' + name + '</p>';
html += '<p>' + age + '</p>';
html += '</div>';
//ES6
const name = 'zhangsan', age = 20;
const html = `<div>
<p>${name}</p>
<p>${age}</p>
</div>`; //使用反引号
console.log(html);
解构赋值
//JS
var obj = {a:200,b:300}
var a = obj.a
var b = obj,b
var arr = ['xxx', 'yyy', 'zzz']
var x = arr[0]
//ES6
const obj = {a:10, b:20, c:30}
const {a, c} = obj //取a,c两个属性
console.log(a)
console,log(c)
const arr = ['xxx', 'yyy', 'zzz']
const [x, y, z] = arr
console.log(x); console.log(y); console.log(z);
块级作用域
//JS
var obj = {a:100, b:200}
for(var item in obj){
console.log(item)
}
console.log(item) //b
//ES6
const obj = {a:100, b:200}
for(let item in obj){
console.log(item)
}
console.log(item) //undefined
函数默认参数
//JS
function(a,b){
if(b = null){
b = 0
}
}
//ES6
function(a, b=0){ //如果b为空,默认b等于0
}
箭头函数
//JS
var arr = [1, 2, 3]
arr.map(function(item){
return item+1
})
//ES6
const arr = [1, 2, 3]
arr.map(item => item+1) //函数只有一个参数,函数里只有一行
arr.map((item, index) => { //函数有多个参数,函数里有多行
console.log(index)
return item + 1
})
- 箭头函数解决了JS中this是window全局变量的问题
- 箭头函数作为普通函数的一个补充,将this指向了函数体之外最近一层的this,而不是向普通JS一样将this指向window变量。
function fn(){
console.log('real',this) //{a:100}
var arr = [1,2,3]
//普通JS
arr.map(function (item){
console.log('js',this) //window
return item + 1
})
//箭头函数
arr.map(item => {
console.log('es6',this) //{a:100}
return item + 1
})
}
fn.call({a:100}) //将{a:100}设置为this