學(xué)習(xí)ES6筆記──工作中常用到的ES6語法

一、let和const
function test() {if(true) {console.log(a)//TDZ,俗稱臨時(shí)死區(qū),用來描述變量不提升的現(xiàn)象let a = 1}}test() // a is not definedfunction test() {if(true) {let a = 1}console.log(a)}test() // a is not defined
function test() {if(true) {let a = 1console.log(a)}}test() // 1
const type = {a: 1}type.a = 2 //沒有直接修改type的值,而是修改type.a的屬性值,這是允許的。console.log(type) // {a: 2}
for(var i = 0; i < 5; i++) {setTimeout(() => {console.log(i) //5, 5, 5, 5, 5}, 0)}console.log(i) //5 i跳出循環(huán)體污染外部函數(shù)//將var改成let之后for(let i = 0; i < 5; i++) {setTimeout(() => {console.log(i) // 0,1,2,3,4}, 0)}console.log(i)//i is not defined i無法污染外部函數(shù)
var mySymbol=Symbol();console.log(typeof mySymbol) //"symbol"
二、字符串
// 以前的多行字符串我們這么寫:console.log("hello world 1\n\hello cala");// "hello world// hello cala"//有了模板字符串之后console.log(`hello worldstring text line 2`);// "hello world// hello cala"
var name="cala";var age=22;console.log(`hello,I'am ${name},my age is ${age}`)//hello,I'am cala,my age is 22
let t = 'abcdefg'if(t.includes('cde')) {console.log(2)}//true
let t = 'abcdefg'if(t.startsWith('ab')) {console.log(2)}//true
let t = 'abcdefg'if(t.endsWith('fg')) {console.log(2)}//true
三、函數(shù)
在ES5中,我們給函數(shù)傳參數(shù),然后在函數(shù)體內(nèi)設(shè)置默認(rèn)值,如下面這種方式。
function a(num, callback) {num = num || 6callback = callback || function (data) {console.log('ES5: ', data)}callback(num * num)}a() //ES5: 36,不傳參輸出默認(rèn)值//你還可以這樣使用callbacka(10, function(data) {console.log(data * 10) // 1000, 傳參輸出新數(shù)值})
function a(num = 6, callback = function (data) {console.log('ES6: ', data)}) {callback(num * num)}a() //ES6: 36, 不傳參輸出默認(rèn)值a(10, function(data) {console.log(data * 10) // 1000,傳參輸出新數(shù)值})
四、箭頭函數(shù)(=>)
const arr = [5, 10]const s = arr.reduce((sum, item) => sum + item)console.log(s) // 15
普通函數(shù):
1、函數(shù)作為全局函數(shù)被調(diào)用時(shí),this指向全局對(duì)象
2、函數(shù)作為對(duì)象中的方法被調(diào)用時(shí),this指向該對(duì)象
3、函數(shù)作為構(gòu)造函數(shù)的時(shí)候,this指向構(gòu)造函數(shù)new出來的新對(duì)象
4、還可以通過call,apply,bind改變this的指向
箭頭函數(shù):
1、箭頭函數(shù)沒有this,函數(shù)內(nèi)部的this來自于父級(jí)最近的非箭頭函數(shù),并且不能改變this的指向。
2、箭頭函數(shù)沒有super
3、箭頭函數(shù)沒有arguments
4、箭頭函數(shù)沒有new.target綁定。
5、不能使用new
6、沒有原型
7、不支持重復(fù)的命名參數(shù)。
const s = a => aconsole.log(s(2)) // 2
//ES5普通函數(shù)function Man(){this.age=22;return function(){this.age+1;}}var cala=new Man();console.log(cala())//undefined//ES6箭頭函數(shù)function Man(){this.age=22;return () => this.age+1;}var cala=new Man();console.log(cala())//23
//沒有argumentsvar foo=(a,b)=>{return arguments[0]*arguments[1]}console.log(foo(3,5))//arguments is not defined//沒有原型var Obj = () => {};console.log(Obj.prototype);// undefined//不能使用new 關(guān)鍵字var Obj = () => {"hello world"};var o = new Obj();// TypeError: Obj is not a constructor
const arr = [10, 50, 30, 40, 20]const s = arr.sort((a, b) => a - b)console.log(s) // [10,20,30,40,50]
2、尾調(diào)用是函數(shù)最后一條語句
3、尾調(diào)用結(jié)果作為函數(shù)返回
在ES5時(shí)代,我們不推薦使用遞歸,因?yàn)檫f歸會(huì)影響性能。
但是有了尾調(diào)用優(yōu)化之后,遞歸函數(shù)的性能有了提升。
//新型尾優(yōu)化寫法"use strict";function a(n, p = 1) {if(n <= 1) {return 1 * p}let s = n * preturn a(n - 1, s)}//求 1 x 2 x 3的階乘let sum = a(3)console.log(sum) // 6
五、ES6對(duì)象新增方法
var o1 = { a: 1 };var o2 = { b: 2 };var o3 = { c: 3 };var obj = Object.assign(o1, o2, o3);console.log(obj); // { a: 1, b: 2, c: 3 }console.log(o1); // { a: 1, b: 2, c: 3 }, 注意目標(biāo)對(duì)象自身也會(huì)改變。
var o1 = { a: 1, b: 1, c: 1 };var o2 = { b: 2, c: 2 };var o3 = { c: 3 };var obj = Object.assign({}, o1, o2, o3);console.log(obj); // { a: 1, b: 2, c: 3 }
六、Map和Set
Array的indexOf方法比Set的has方法效率低下
let set = new Set()// Set轉(zhuǎn)化為數(shù)組let arr = Array.from(set)let arr = [...set]// 實(shí)例屬性(繼承自Set)set.constructor === Setset.size// 操作方法set.add(1) // 添加一個(gè)值set.delete(1) //刪除一個(gè)值set.has(1) //判斷是否有這個(gè)值(Array中的indexOf)set.clear() //清除所有值// 獲取用于遍歷的成員方法(Set的遍歷順序就是插入順序)set.keys() // 返回鍵名的遍歷器set.values() // 返回鍵值得遍歷器set.entries() // 返回鍵值對(duì)的遍歷器set.forEach() // 循環(huán)遍歷每個(gè)值(和Array的方法一致)for (let key of set.keys()){}for (let val of set.values()){}for (let entry of set.entries()){}// 使用數(shù)組方法來處理set值set = new Set(arr)set = new Set([...set].map((x) => x = x * 2))set = new Set([...set].filter((x) => x > 2))
let map = new Map()// 實(shí)例屬性(繼承自Map)map.constructor === Mapmap.size// 操作方法map.set(1,2)map.get(1)map.delete(1)map.has(1)map.clear()// 遍歷方法map.keys()map.values()map.entries()map.forEach()// Map和數(shù)組的轉(zhuǎn)換map = new Map([['key','val'],[2,1]]) // 要求雙成員數(shù)組let arr = [...map]// 值得注意的是Map的鍵是跟內(nèi)存綁定的map.set([1], 's')map.get([1])let arr = [1]let arr1 = [1]map.set(arr, 's')map.get(arr)map.set(arr1, 's')map.get(arr1)
七、迭代器(Iterator)
//數(shù)組const arr = ['a', 'b', 'c'];for(let v of arr.entries()) {console.log(v)}// [0, 'a'] [1, 'b'] [2, 'c']//Setconst arr = new Set(['a', 'b', 'c']);for(let v of arr.entries()) {console.log(v)}// ['a', 'a'] ['b', 'b'] ['c', 'c']//Mapconst arr = new Map();arr.set('a', 'a');arr.set('b', 'b');for(let v of arr.entries()) {console.log(v)}// ['a', 'a'] ['b', 'b']
//數(shù)組const arr = ['a', 'b', 'c'];for(let v of arr.values()) {console.log(v)}//'a' 'b' 'c'//Setconst arr = new Set(['a', 'b', 'c']);for(let v of arr.values()) {console.log(v)}// 'a' 'b' 'c'//Mapconst arr = new Map();arr.set('a', 'a');arr.set('b', 'b');for(let v of arr.values()) {console.log(v)}// 'a' 'b'
//數(shù)組const arr = ['a', 'b', 'c'];for(let v of arr.keys()) {console.log(v)}// 0 1 2//Setconst arr = new Set(['a', 'b', 'c']);for(let v of arr.keys()) {console.log(v)}// 'a' 'b' 'c'//Mapconst arr = new Map();arr.set('a', 'a');arr.set('b', 'b');for(let v of arr.keys()) {console.log(v)}// 'a' 'b'
const obj = {a: 1,b: 2,*[Symbol.iterator]() {for(let i in obj) {yield [i, obj[i]]}}}for(let [key, value] of obj) {console.log(key, value)}// 'a' 1, 'b' 2
const str = 'abc';for(let v of str) {console.log(v)}// 'a' 'b' 'c'
ES6給數(shù)組添加了幾個(gè)新方法:find()、findIndex()、fill()、copyWithin()
const arr = [1, "2", 3, 3, "2"]console.log(arr.find(n => typeof n === "number")) // 1
const arr = [1, "2", 3, 3, "2"]console.log(arr.findIndex(n => typeof n === "number")) // 0
arr.fill(value, start, end)
arr.copyWithin(target, start, end)const arr = [1, 2, 3, 4, 5]console.log(arr.copyWithin(3)) // [1,2,3,1,2] 從下標(biāo)為3的元素開始,復(fù)制數(shù)組,所以4, 5被替換成1, 2const arr1 = [1, 2, 3, 4, 5]console.log(arr1.copyWithin(3, 1)) // [1,2,3,2,3] 從下標(biāo)為3的元素開始,復(fù)制數(shù)組,指定復(fù)制的第一個(gè)元素下標(biāo)為1,所以4, 5被替換成2, 3const arr2 = [1, 2, 3, 4, 5]console.log(arr2.copyWithin(3, 1, 2)) // [1,2,3,2,5] 從下標(biāo)為3的元素開始,復(fù)制數(shù)組,指定復(fù)制的第一個(gè)元素下標(biāo)為1,結(jié)束位置為2,所以4被替換成2
評(píng)論
圖片
表情
