1、const和let
在ES6之前,我們都是用var關鍵字聲明變量。無論聲明在何處,都會被視爲聲明在函數的最頂部(不在函數內即在全局作用域的最頂部)。這就是函數變量提升例如:
function aa() {
if(flag) {
var test = 'hello man'
} else {
console.log(test)
}
}
實際上是
function aa() {
var test // 變量提升,函數最頂部
if(flag) {
test = 'hello man'
} else {
//此處訪問 test 值爲 undefined
console.log(test)
}
//此處訪問 test 值爲 undefined
}
而let和const都是塊級作用域(一個花括號內可認爲塊級作用域,如函數或代碼塊內)
const聲明必須賦值所以一般用於常量,無法被修改
2、字符串
模板字符串 使用``來定義其中可以加上${}拼接賦值
用途一:快速賦值
//ES5
var name = 'lux'
console.log('hello' + name)
//es6
const name = 'lux'
console.log(`hello ${name}`) //hello lux
用途二:多行字符串
// ES5
var msg = "Hi \
man!
"
// ES6
const template = `<div>
<span>hello world</span>
</div>`
常用字符串處理方法:
1.includes:判斷是否包含然後直接返回布爾值
2.repeat: 獲取字符串重複n次
3. startsWith 和 endsWith 判斷是否以 給定文本 開始或者結束
4. padStart 和 padEnd 填充字符串,應用場景:時分秒
3、函數
默認傳參
function action(num = 200) {
console.log(num)
}
action(0) // 0
action() //200
action(300) //300
箭頭函數
傳參大於等於兩個時用括號包裹,this可繼承
//例如:
[1,2,3].map(x => x + 1)
//等同於:
[1,2,3].map((function(x){
return x + 1
}).bind(this))
4、解構以及展開運算符
解構
//對象
const people = {
name: 'lux',
age: 20
}
const { name, age } = people
console.log(`${name} --- ${age}`)
//數組
const color = ['red', 'blue']
const [first, second] = color
console.log(first) //'red'
console.log(second) //'blue'
展開運算符...
//數組
const number = [1,2,3,4,5]
const [first, ...rest] = number
console.log(rest) //2,3,4,5
//對象
const user = {
username: 'lux',
gender: 'female',
age: 19,
address: 'peking'
}
const { username, ...rest } = user
console.log(rest) //{"address": "peking", "age": 19, "gender": "female"
}
5.import 和 export
6、promise