1. Let 和 Const
{
var a = 10
let b = 20
const c = 30
}
a // 10
b // Uncaught ReferenceError: b is not defined
c // c is not defined
let d = 40
const e = 50
d = 60
d // 60
e = 70 // VM231:1 Uncaught TypeError: Assignment to constant variable.
2.類(Class)
function Person(name, age) {
this.name = name
this.age = age
}
Person.prototype.information = function () {
return 'My name is ' + this.name + ', I am ' + this.age
}
//es6
class Person {
constructor(name, age) {
this.name = name
this.age = age
}
information() {
return 'My name is ' + this.name + ', I am ' + this.age
}
}
3. 箭頭函數(shù)(Arrow function)
var list = [1, 2, 3, 4, 5, 6, 7]
var newList = list.map(function (item) {
return item * item
})
//es6
const list = [1, 2, 3, 4, 5, 6, 7]
const newList = list.map(item => item * item)
4.函數(shù)參數(shù)默認(rèn)值(Function parameter defaults)
function config (data) {
var data = data || 'data is empty'
}
//es6
const config = (data = 'data is empty') => {}
例1:
// 給方法添加默認(rèn)參數(shù)值
function foo( a = 5, b = 10) {
console.log( a + b);
}
foo(); // 15
foo( 7, 12 ); // 19
foo( undefined, 8 ); // 13
foo( 8 ); // 18
foo( null ); // 10 as null is coerced to 0
例2:
// 默認(rèn)參數(shù)值也可以是表達(dá)式或者函數(shù)
function foo( a ) { return a * 4; }
// y = x + 4, z = foo(x)
function bar( x = 2, y = x + 4, z = foo(x)) {
console.log([ x, y, z ]);
}
bar(); // [ 2, 6, 8 ]
bar( 1, 2, 3 ); //[ 1, 2, 3 ]
bar( 10, undefined, 3 ); // [ 10, 14, 3 ]
例3:
// 對(duì)象參數(shù)默認(rèn)值岛都,如果參數(shù)為空,則會(huì)拋出異常
function show({ title = "title", width = 100, height = 200 }) {
console.log( `${title} ${width} ${height}` );
}
show() // Cannot destructure property `title` of 'undefined' or 'null'.
show({}) // title 100 200
// 解決辦法:
function show({ title = "title", width = 100, height = 200 } = {}) {
console.log( `${title} ${width} ${height}` );
}
show(); // title 100 200
show({width: 200}) // title 200 200
5.模板字符串(Template string)
var name = 'kris'
var age = 24
var info = 'My name is ' + this.name + ', I am ' + this.age
//es6
const name = 'kris'
const age = 24
const info = `My name is ${name}, I am ${age}`
函數(shù)分兩種情況:
- 函數(shù)本身,同樣會(huì)調(diào)用它的tostring()方法
- 直接調(diào)用函數(shù)贿堰,則輸出函數(shù)的返回值
var fn1 = function(){
console.log('hello vuex');
}
var fn2 = function(){
return 'hello vue-router'
}
`xxx ${fn1}`//xxx function fn(){....}
`xxx ${fn1()}`//xxx underfind
`xxx ${fn2()}`//xxx hello vue-router
6.解構(gòu)賦值(Destructuring assignment)
例1:
let a = 10
let b = 20
[a, b] = [b, a]
例2(聲明多個(gè)變量):
// 聲明變量
let age = 22
let name = 'guodada'
let sex = 1
// better
let [age, name, sex] = [22, 'aa', 1]
console.log(age, name, sex) //22 "aa" 1
例3(使用在對(duì)象中):
const obj = {
name: {
firstName: 'guo',
lastName: 'dada'
}
}
// 提取變量
const firstName = obj.name.firstName
const lastName = obj.name.lastName
// better
const { firstName, lastName } = obj.name
例4(使用在函數(shù)中):
// 在參數(shù)中結(jié)構(gòu)賦值至壤,獲取參數(shù), 當(dāng)參數(shù)多的使用時(shí)候十分方便
function Destructuring({ name, age }) {
return { name, age } // 相當(dāng)于 { name: name, age: age } , 可以簡(jiǎn)寫(xiě)
}
const params = { name: 'guodada', age: 22 }
Destructuring(params)
例5:key變量重命名, first --> firstName
// key變量重命名痕檬, first --> firstName
const person = {
first: 'foo',
last: 'tom',
};
const { first: firstName } = person;
console.log(firstName); // foo
例6:默認(rèn)值
// 默認(rèn)值
const settings = {
speed: 150
}
const { speed = 750, width = 500 } = settings;
console.log(speed); // 150
console.log(width); // 500
// 可能不存在的key
const { middle: middleName = 'midname' } = person;
console.log(middleName); // 'midname'
例6:嵌套賦值
// 嵌套賦值
const user = {
id: 339,
name: 'Fred',
age: 42,
education: {
degree: 'Masters'
}
};
const {education: {degree}} = user;
console.log(degree); //prints: Masters
如果嵌套的屬性不存在
// 如果嵌套的屬性不存在
const user = {
id: 339,
name: 'Fred',
age: 42
};
const {education: {degree}} = user; // TypeError: Cannot match against 'undefined' or 'null'.
// 解決辦法:
const user = {
id: 339,
name: 'Fred',
age: 42
};
const {education: {degree} = {}} = user;
console.log(degree); //prints: undefined
7.擴(kuò)展操作符(Spread operator)
function sum(x, y, z) {
return x + y + z;
}
var list = [5, 6, 7]
var total = sum.apply(null, list)
//es6
const sum = (x, y, z) => x + y + z
const list = [5, 6, 7]
const total = sum(...list)
主要用途:
let a = [1, 2, 3]
let b = [...a] // b是一個(gè)新的數(shù)組碴开,內(nèi)容和a一樣
let c = [...a, 4, 5, 6]
let car = { type: 'vehicle ', wheels: 4};
let newCar = {...car}
console.log(newCar); // { type: 'vehicle ', wheels: 4}
// 合并對(duì)象屬性,后邊的屬性會(huì)覆蓋前邊的监右,可用于修改對(duì)象的某個(gè)屬性值
let car2 = {...car, type: 'vehicle2', wheels: 2} // {type: "vehicle2", wheels: 2}
function foo(...args) {
console.log(args);
}
foo( 'car', 54, 'tree'); // console.log 輸出 [ 'car', 54, 'tree' ]
8.對(duì)象屬性簡(jiǎn)寫(xiě)(Object attribute shorthand)
var cat = 'Miaow'
var dog = 'Woof'
var bird = 'Peet peet'
var someObject = {
cat: cat,
dog: dog,
bird: bird
}
//es6
let cat = 'Miaow'
let dog = 'Woof'
let bird = 'Peet peet'
let someObject = {
cat,
dog,
bird
}
console.log(someObject)
//{
// cat: "Miaow",
// dog: "Woof",
// bird: "Peet peet"
//}
9.for...of
for...of語(yǔ)句在可迭代對(duì)象(包括 Array边灭,Map,Set健盒,String绒瘦,TypedArray,arguments 對(duì)象等等)上創(chuàng)建一個(gè)迭代循環(huán)味榛,調(diào)用自定義迭代鉤子椭坚,并為每個(gè)不同屬性的值執(zhí)行語(yǔ)句。
const array1 = ['a', 'b', 'c'];
for (const element of array1) {
console.log(element)
}
// "a"
// "b"
// "c"
10. Set
const numbers = [2,3,4,4,2,3,3,4,4,5,5,6,6,7,5,32,3,4,5]
console.log([...new Set(numbers)])
// [2, 3, 4, 5, 6, 7, 32]
11. Map
Map 對(duì)象保存鍵值對(duì)搏色。任何值(對(duì)象或者原始值) 都可以作為一個(gè)鍵或一個(gè)值善茎。
例子如下,我們甚至可以使用NaN來(lái)作為鍵值:
var myMap = new Map();
myMap.set(NaN, "not a number");
myMap.get(NaN); // "not a number"
var otherNaN = Number("foo");
myMap.get(otherNaN); // "not a number"
12.Array對(duì)象的擴(kuò)展
(1)Array.prototype.from:轉(zhuǎn)換具有Iterator接口的數(shù)據(jù)結(jié)構(gòu)為真正數(shù)組频轿,返回新數(shù)組垂涯。
console.log(Array.from('foo')) // ["f", "o", "o"]
console.log(Array.from([1, 2, 3], x => x + x)) // [2, 4, 6]
// 等同于
Array.from([1,2,3].map(x => x * x))
Array.from()可以將各種值轉(zhuǎn)為真正的數(shù)組,并且還提供map功能航邢。這實(shí)際上意味著耕赘,只要有一個(gè)原始的數(shù)據(jù)結(jié)構(gòu),你就可以先對(duì)它的值進(jìn)行處理膳殷,然后轉(zhuǎn)成規(guī)范的數(shù)組結(jié)構(gòu)操骡,進(jìn)而就可以使用數(shù)量眾多的數(shù)組方法。
Array.from({ length: 2 }, () => 'jack')// ['jack', 'jack']
(2)Array.prototype.of():轉(zhuǎn)換一組值為真正數(shù)組赚窃,返回新數(shù)組册招。
Array.of(7) // [7]
Array.of(1, 2, 3) // [1, 2, 3]
Array(7) // [empty, empty, empty, empty, empty, empty]
Array(1, 2, 3) // [1, 2, 3]
(3)Array.prototype.find():返回第一個(gè)符合條件的成員
const array1 = [5, 12, 8, 130, 44]
const found = array1.find(element => element > 10)
console.log(found) // 12
//如果沒(méi)找到,就返回undefined
(4)Array.prototype.keys():返回以索引值為遍歷器的對(duì)象
const array1 = ['a', 'b', 'c']
const iterator = array1.keys()
for (const key of iterator) {
console.log(key)
}
// 0
// 1
// 2
(5)Array.prototype.values():返回以屬性值為遍歷器的對(duì)象
const array1 = ['a', 'b', 'c']
const iterator = array1.values()
for (const key of iterator) {
console.log(key)
}
// a
// b
// c
(6)Array.prototype.entries():返回以索引值和屬性值為遍歷器的對(duì)象
const array1 = ['a', 'b', 'c']
const iterator = array1.entries()
console.log(iterator.next().value) // [0, "a"]
console.log(iterator.next().value) // [1, "b"]
13.Array.prototype.includes()
includes() 方法用來(lái)判斷一個(gè)數(shù)組是否包含一個(gè)指定的值勒极,根據(jù)情況是掰,如果包含則返回 true,否則返回false辱匿。
const array1 = [1, 2, 3]
console.log(array1.includes(2)) // true
const pets = ['cat', 'dog', 'bat']
console.log(pets.includes('cat')) // true
console.log(pets.includes('at')) // false
14. Object.keys()键痛、Object.values()、Object.entries() 對(duì)象轉(zhuǎn)鍵值對(duì)匾七、Object.fromEntries() 鍵值對(duì)轉(zhuǎn)對(duì)象
const object1 = {
a: 'somestring',
b: 42
}
console.log(Object.keys(object1)) // ["a", "b"]
const object1 = {
a: 'somestring',
b: 42,
c: false
}
console.log(Object.values(object1)) // ["somestring", 42, false]
const object1 = {
a: 'somestring',
b: 42
}
for (let [key, value] of Object.entries(object1)) {
console.log(`${key}: ${value}`)
}
// "a: somestring"
// "b: 42"
Object.fromEntries() 方法把鍵值對(duì)列表轉(zhuǎn)換為一個(gè)對(duì)象絮短,它是Object.entries()的反函數(shù)。
const entries = new Map([
['foo', 'bar'],
['baz', 42]
])
const obj = Object.fromEntries(entries)
console.log(obj) // Object { foo: "bar", baz: 42 }
15. padStart()
padStart() 方法用另一個(gè)字符串填充當(dāng)前字符串(重復(fù)昨忆,如果需要的話)戚丸,以便產(chǎn)生的字符串達(dá)到給定的長(zhǎng)度。填充從當(dāng)前字符串的開(kāi)始(左側(cè))應(yīng)用的。
代碼如下:
const str1 = '5'
console.log(str1.padStart(2, '0')) // "05"
const fullNumber = '2034399002125581'
const last4Digits = fullNumber.slice(-4)
const maskedNumber = last4Digits.padStart(fullNumber.length, '*')
console.log(maskedNumber) // "************5581"
16. padEnd()
padEnd() 方法會(huì)用一個(gè)字符串填充當(dāng)前字符串(如果需要的話則重復(fù)填充)限府,返回填充后達(dá)到指定長(zhǎng)度的字符串夺颤。從當(dāng)前字符串的末尾(右側(cè))開(kāi)始填充。
const str1 = 'Breaded Mushrooms'
console.log(str1.padEnd(25, '.')) // "Breaded Mushrooms........"
const str2 = '200'
console.log(str2.padEnd(5)) // "200 "
17.對(duì)象擴(kuò)展操作符
ES6中添加了數(shù)組的擴(kuò)展操作符胁勺,讓我們?cè)诓僮鲾?shù)組時(shí)更加簡(jiǎn)便世澜,美中不足的是并不支持對(duì)象擴(kuò)展操作符,但是在ES9開(kāi)始署穗,這一功能也得到了支持寥裂,例如:
var obj1 = { foo: 'bar', x: 42 };
var obj2 = { foo: 'baz', y: 13 };
var clonedObj = { ...obj1 };
// 克隆后的對(duì)象: { foo: "bar", x: 42 }
var mergedObj = { ...obj1, ...obj2 };
// 合并后的對(duì)象: { foo: "baz", x: 42, y: 13 }
上面便是一個(gè)簡(jiǎn)便的淺拷貝。這里有一點(diǎn)小提示案疲,就是Object.assign() 函數(shù)會(huì)觸發(fā) setters封恰,而展開(kāi)語(yǔ)法則不會(huì)。所以不能替換也不能模擬Object.assign() 褐啡。
如果存在相同的屬性名诺舔,只有最后一個(gè)會(huì)生效。