1. 程式人生 > >ES6必知必會 (三)—— 數組和對象的拓展

ES6必知必會 (三)—— 數組和對象的拓展

prop div BE targe 繼承 常見 屬性和方法 include 表達式

數組的擴展

1.拓展運算符(‘...‘),它相當於rest參數的逆運算,用於將一個數組轉換為用逗號分隔的參數序列;

console.log(...[1, 2, 3])
// 1 2 3
console.log(1, ...[2, 3, 4], 5)
// 1 2 3 4 5

2.如果擴展運算符後面是一個空數組,則不產生任何效果;

[...[], 1]
// [1]

3.常見的拓展運算符的應用:

//合並數組

let arr1 = [1,2];
let arr2 = [3,4];
let arr3 = [5,6];

let newArr = [...arr1 , ...arr2 , ...arr3];  //等同於ES5 [].concat( arr1 , arr2 , arr3 )
// [1,2,3,4,5,6]


//與解構賦值結合(用於生成數組)

const [ val , ...rest] = [1, 2, 3, 4, 5];
val // 1
rest  // [2, 3, 4, 5]


//將字符串轉為真正的數組

let str = ‘mine‘;
[...str]  // ["m","i","n","e"]



//可以將類數組轉化成正真的數組

 let arrayLike = {
    0 : ‘div.class1‘ ,
    1 : ‘div.class2‘ ,
    2 : ‘div.class3‘ ,
    length : 3
}
console.log([...arrayLike])  // ["div.class1","div.class2","div.class3"]

4.新增 Array.from 方法,可以將類似數組的對象(array-like object)和可遍歷(iterable)的對象轉化成真正的數組;該方法還可以接受第二個參數,作用類似於數組的map方法,用來對每個元素進行處理,將處理後的值放入返回的數組;

let arr = [ 1 , 2 , 3];

arr.map( x => x * x);
// [ 1 , 4 , 9 ]

Array.from(arr, (x) => x * x)
// [ 1 , 4 , 9 ]

5.新增 Array.of 方法 ,用於將一組值,轉換為數組(該方法基本上可以用來替代Array()或new Array(),避免出現參數不同而導致的重載);

//傳統Array
   
Array() // []
Array(3) // [, , ,]
Array(1, 2, 3) // [1, 2, 3]

//Array.of

Array.of() // []
Array.of(undefined) // [undefined]
Array.of(1) // [1]
Array.of(1, 2) // [1, 2]

6.數組實例方法 find() 用於找出第一個符合條件的數組成員,該方法的參數是一個回調函數,該回調函數可以接收三個參數,依次是當前元素,當前元素索引,數組本身;如果查找成功,返回符合條件的第一個成員,如果沒有符合條件的成員,則返回undefined;

var arr = [1, 2, 4, 5];
var r = arr.find(function( element , index , self ){
    return element % 2 == 0;
})
r  // 2

7.數組實例方法 findIndex() , 該方法的參數與 find() 一樣 , 不同的是該方法 返回的是第一個符合條件的數組成員的位置,如果所有成員都不符合條件,則返回-1;

var arr = [1, 2, 4, 5];
var r = arr.find(function( element , index , self ){
    return element % 2 == 0;
})
r  // 1

ps:find() 和 findIndex() 這兩個方法都可以發現NaN,彌補了數組的IndexOf方法的不足。

8.數組實例方法 includes() , 方法返回一個布爾值,表示某個數組是否包含給定的值,與字符串的includes方法類似;該方法接收兩個參數,第一個參數是要查找的成員,第二個參數表示搜索的起始位置(如果為負數,則表示倒數的位置,如果大於數組長度,則會重置為從0開始)

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

[1, 2, 3].includes(3, 3);  // false
[1, 2, 3].includes(3, -1); // true

對象的拓展

1.ES6 允許直接寫入變量和函數,作為對象的屬性和方法(在對象中,直接寫變量時,屬性名為變量名, 屬性值為變量的值)

//屬性簡寫
var foo = ‘bar‘;
var obj = {foo};
obj // { foo : "bar" }

//變量簡寫
var mine = {
    foo , 
    method(){
        //to do
    }
}

2.ES6 允許字面量定義對象時,用表達式作為對象的屬性名或者方法名,即把表達式放在方括號內;

let propKey = ‘foo‘;

let obj = {
  [propKey]: true,
  [‘a‘ + ‘bc‘]: 123,
  [‘s‘ + ‘ay‘](){
    console.log(‘hello world‘)
  }
}
obj // {"foo":true,"abc":123}
obj.say()  // ‘hello world‘

3.新增 Object.is() 方法,用來比較兩個值是否嚴格相等,與嚴格比較運算符(===)的行為基本一致,不同之處在於一是+0不等於-0,二是NaN等於自身。

+0 === -0 //true
NaN === NaN // false

Object.is(+0, -0) // false
Object.is(NaN, NaN) // true

4.新增 Object.assign 方法用於對象的合並,將源對象(source)的所有可枚舉屬性,復制到目標對象(target),第一個參數是目標對象,後面的參數都是源對象;

var target = { a: 1 };

var source1 = { b: 2 };
var source2 = { c: 3 };

Object.assign(target, source1, source2);
target // {a:1, b:2, c:3}

ps:如果目標對象與源對象有同名屬性,或多個源對象有同名屬性,則後面的屬性會覆蓋前面的屬性。

var target = { a: 1, b: 1 };

var source1 = { b: 2, c: 2 };
var source2 = { c: 3 };

Object.assign(target, source1, source2);
target // {a:1, b:2, c:3}

該方法不能用於目標對象是 undefined 和 null 上, 會報錯;

5.Object.assign 方法實行的是淺拷貝,而不是深拷貝。如果源對象某個屬性的值是對象,那麽目標對象拷貝得到的是這個對象的引用,修改會對原對象造成影響;

var obj1 = {a: {b: 1}};
var obj2 = Object.assign({}, obj1);

obj1.a.b = 2;
obj2.a.b     // 2

6.Object.assign 方法常用於以下幾個方面

  • 為對象添加屬性
    <pre>
    var _this = {};
    Object.assign( _this , { name : ‘mine‘ } );
    _this // { name : ‘mine‘ }
    </pre>

  • 為對象添加方法
    <pre>
    var _this = {};
    Object.assign( _this , { func(){ console.log(‘hello world‘) } } );
    _this.func() // hello world
    </pre>

  • 克隆對象
    <pre>
    var _this = { name : ‘mine‘ };
    Object.assign( {} , _this );
    </pre>

  • 合並多個對象
    <pre>
    var _this = {};
    var source1 = { name : ‘mine‘ };
    var source2 = { mail : ‘your‘ };
    Object.assign( _this , source1 , source2 );
    _this // {"name":"mine","mail":"your"}
    </pre>

  • 為屬性指定默認值
    <pre>
    var default = { name : ‘mine‘ , mail : ‘your‘ }
    function processContent(options) {
    options = Object.assign({}, default , options);
    // to do
    }
    </pre>
    7.Object.setPrototypeOf方法的作用與_proto_相同,用來設置一個對象的prototype對象,返回參數對象本身。它是 ES6 正式推薦的設置原型對象的方法。
    <pre>
    let proto = {};
    let obj = { x: 10 };
    Object.setPrototypeOf(obj, proto);

    proto.y = 20;
    proto.z = 40;

    obj.x // 10
    obj.y // 20
    obj.z // 40
    </pre>

8.Object.getPrototypeOf()方法,該方法與Object.setPrototypeOf方法配套,用於讀取一個對象的原型對象。

9.Object.keys(),Object.values(),Object.entries() 除第一個外,後面兩個是ES6新增的方法,用於遍歷對象,返回都是數組,成員是參數對象自身的(不含繼承的)所有可遍歷(enumerable)屬性的鍵、值和鍵值對數組。

let obj = { a : 1 , b : ‘hello‘ }

Object.keys( obj );     // ["a","b"]
Object.values( obj );   // [1,"hello"]
Object.entries( obj );  // [["a",1],["b","hello"]]




ES6必知必會 (三)—— 數組和對象的拓展