深入理解es6(上)


一、let和const

1、let與var的區別

不存在變量提升
塊級作用域
不允許重復聲明

2、const常量

const與let一樣,唯一區別在於聲明的常量不能被修改

二、解構賦值

es6按照一定模式,從數組和對象中提取值,對變量進行賦值,被稱為解構

1、數組的解構

  • "模式匹配",只要等號兩邊的模式相同,左邊的變量就會被賦予對應的值,如果右邊不是數組就會報錯
  • 基本用法:
let [a, b, c] = [1, 2, 3] // a=1, b=2, c=3

let [a1, b1=2] = [1] // a1=1, b1=2 //指定默認值

let [d, [e], f] = [1, [2], 3] // 嵌套數組解構 d=1, e=2, f=3

let [g, ...h] = [1, 2, 3] // 數組拆分 g=1, h=[2, 3]

let [i,,j] = [1, 2, 3] // 不連續解構 i=1, j=3

let [k,l] = [1, 2, 3] // 不完全解構 k=1, l=2

2、對象的解構

與數組不同的是,變量的解構沒有順序問題,變量必須與屬性同名才能解構
基本用法:

let {a, b} = {a:'aa', b:'bb'} //a='aa' b='bb'

//設置默認值
let {x, y = 5} = {x: 1}; //x= 1 y=5

//允許別名,a的值將失效
let {a:a1,b} = {a:'aa', b:'bb'} //a1='aa' b='bb' 

let obj = {a:'aa', b: {c:'c'}}
let {a, b:{c}} = obj // 嵌套解構 a='aa' c='c'


3、字符串的解構

let [a, b, c] = 'hello' // a='h' b='e' c='l'

4、函數的解構

function say({name,age}){
    console.log(name + '今年' + age)
} 
say({name:'小明',age:18})

三、字符串的擴展

1、模板字符串

用反引號(`)標識,字符串中嵌入變量用${}

2、新增方法

查找字符串,返回布爾值

let str = 'hello world'
//返回布爾值,表示是否找到了參數字符串
str.includes('r')  //true 

//返回布爾值,表示參數字符串是否在原字符串的頭部
str.startsWith('hello')  //true

//返回布爾值,表示參數字符串是否在原字符串的尾部
str.endsWith('d')  //true

去空格

let str = '   hello world      '
//消除首尾的空格
str.trim()  //'hello world'

//消除字符串頭部的空格
str.trimStart()  //'hello world   '

//消除尾部的空格
str.trimEnd()  //'   hello world'

四、數組的擴展

es5新增的方法:
forEach、map、filter、some、every、reduce

1、Array.from將類似數組的對象轉為數組

//類似數組的對象
let obj = {
    0:'a',
    1:'b',
    2:'c',
    length:3
}
//es5寫法
var arr = [].slice.call(obj);
//es6寫法
var arr1 = Array.from(obj);

// arguments對象
function foo() {
  var args = Array.from(arguments);
  // ...
}

2、Array.of方法用於將一組值,轉換為數組

    Array.of(3, 11, 8) // [3,11,8]
    Array.of(3) // [3]

3、find/findIndex查找符合條件的元素

//find方法找出第一個符合條件的數組成員
let arr = [1, 4, -5, 10];
let val = arr.find((item,index,arr)=>{
    return item > 1;
})
//val 4

//findIndex返回第一個符合條件的數組成員的位置
let index = arr.find((item,index,arr)=>{
    return item > 1;
})
//index 1

4、entries(),keys(),values()用於遍歷數組

可以用for...of循環進行遍歷,唯一的區別是keys()是對鍵名的遍歷、values()是對鍵值的遍歷,entries()是對鍵值對的遍歷。

let arr = ['a','b','c']

//遍歷數組的鍵名
for(let index of arr.keys()){
    console.log(index)
}
//0 1 2 

//遍歷數組的鍵值
for(let value of arr.values()){
    console.log(value)
}
//'a' 'b' 'c'

//遍歷數組的鍵值對
for(let [index,value] of arr.entries()){
    console.log(index,value)
}
//0 'a' 
//1 'b'
//2 'c'

5、includes()表示是否包含某個值

[1, 2, 3].includes(2)     // true
[1, 2, 3].includes(4)     // false
[1, 2, NaN].includes(NaN) // true

//第二個參數表示搜索的開始位置,負數表示倒數位置
[1, 2, 3].includes(3, 3);  // false
[1, 2, 3].includes(3, -1); // true

6、數組的擴展運算符 ...

可以把數組展開成用逗號隔開的一組值

let arr = [1,2,3,4,5,6,7]
//復制數組
let arr1 = [...arr]

//合並數組
let arr2 = [...arr,8] // [1,2,3,4,5,6,7,8]

//展開參數
Math.max(...arr) //7

//剩余參數(解構賦值)
let [a,...b] = arr
//a 1
//b [2,3,4,5,6,7]

//轉Set (同時去重)
let arr3 = [...new Set(arr)]

五、對象的擴展

1、對象的簡寫

  • 當屬性名和屬性值相同時,可以省略屬性值
  • 方法可以省略function
  • 對象的屬性名和方法名允許為變量或者表達式
  • 例如:
let name = '小明'
let age ="age1"
let person = {
    name,
    [age]:18,
    ['hei'+'ght']:180,
    sayName(){
        console.log(this.name)
    }
}
person.sayName();
console.log(person)

2、對象的擴展運算符 ...

同數組擴展運算符,支持對象解構剩余參數,對象合並,復制對象

3、Object.is()

用來比較兩個值是否嚴格相等,等同於 "==="

//唯一不同之處
+0 === -0 //true
NaN === NaN //false
Object.is(+0, -0) // false
Object.is(NaN,NaN) //true

4、Object.assign()

  • 用於對象的合並,第一個參數是目標對象,后面的參數都是源對象
  • 如果目標對象與源對象有同名屬性,則后面會覆蓋前面的屬性
var obj1 = {a:1,b:2}
var obj2 = {b:3,c:4}
console.log(Object.assign(obj1,obj2))
//{a:1, b:3, c:4}

let obj = {a:1, b:2}
Object.assign(obj) === obj // true

//參數不是對象會轉成對象再返回
typeof Object.assign(2) // "object"

//undefined和null無法轉成對象,作為第一個參數會報錯
Object.assign(undefined) // 報錯
Object.assign(null) // 報錯

Object.assign(obj, undefined) === obj // true
Object.assign(obj, null) === obj // true

5、Object.setPrototypeOf(),Object.getPrototypeOf()

  • Object.setPrototypeOf()用來設置一個對象的prototype對象
  • Object.getPrototypeOf()用於讀取一個對象的原型對象
//設置obj對象上的__proto__原型對象為proto對象
let proto = {};
let obj = { x: 10 };
Object.setPrototypeOf(obj, proto);

6、Object.keys(),Object.values(),Object.entries()

使用for...of可以遍歷對象的鍵名,鍵值,鍵值對

var obj = {
    a:1,
    b:2,
    c:3
}
//傳統遍歷對象
for(key in obj){
    console.log(key) //所有鍵值
    console.log(obj[key]) //所有鍵值
}

//es6遍歷
//所有鍵名
for( let index of Object.keys(obj) ){
    console.log(index)
}
//所有鍵值
for( let value of Object.values(obj) ){
    console.log(value)
}
//所有鍵值對
for( let [index,value] of Object.entries(obj) ){
    console.log(index,value)
}

7、Object.fromEntries()

方法是Object.entries()的逆操作,用於將一個鍵值對數組轉為對象

Object.fromEntries([
  ['foo', 'bar'],
  ['baz', 42]
])
// { foo: "bar", baz: 42 }

// 特別適合Map結構
const map = new Map().set('foo', true).set('bar', false);
Object.fromEntries(map)
// { foo: true, bar: false }

六、函數的擴展

1、函數參數的默認值

如果傳入了參數就使用傳入的值,如果沒有就使用默認值

function sum(a=0, b=0){
    return a + b;
}
sum(); //0
sum(1); //1
sum(1,1) //2

2、rest參數

用於獲取函數的多余參數,這樣就不需要使用arguments對象

function add(...value){
    console.log(value)
    //[1,2,3,4]
}
add(1,2,3,4)

3、箭頭函數 =>

使用“箭頭”(=>)定義函數

  • 箭頭函數不需要參數或需要多個參數,就使用一個圓括號代表參數部分
  • 箭頭函數的代碼塊部分多於一條語句,就要使用大括號將它們括起來,並且使用return語句返回
  • 如果箭頭函數直接返回一個對象,必須在對象外面加上括號,否則會報錯
var f = v => v;

// 等同於
var f = function (v) {
  return v;
};

注意:

this指向外部作用域
不可以new,也就是不能用作構造函數
不可以使用argument對象,可以使用rest參數代替

參考至 阮一峰es6


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM