數組的擴展

數組的擴展

展開運算符數組

Array.from()數據結構

Array.of()函數

find(),findIndex()code

fill()對象

entries(),keys(),values()回調函數

includes()it

flat()io

  • 展開運算符console

    console.log(...[1, 2, 3])
    // 1 2 3
    
    console.log(1, ...[2, 3, 4], 5)
    // 1 2 3 4 5
    
    [...document.querySelectorAll('div')]
    // [<div>, <div>, <div>]
  • Array.from()

Array.from方法用於將兩類對象轉爲真正的數組:相似數組的對象(array-like object)和可遍歷(iterable)的對象(包括 ES6 新增的數據結構 Set 和 Map)function

function foo() {
  var args = Array.from(arguments);
  // ...
}
Array.from('hello')
// ['h', 'e', 'l', 'l', 'o']

let namesSet = new Set(['a', 'b'])
Array.from(namesSet) // ['a', 'b']
  • Array.of()

將一組值,轉換爲數組

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

Array()方法沒有參數、一個參數、三個參數時,返回的結果都不同。只有當參數個數很多於 2 個時,Array()纔會返回由參數組成的新數組。參數只有一個正整數時,其實是指定數組的長度

Array.of() // []
Array.of(undefined) // [undefined]
Array.of(1) // [1]
Array.of(1, 2) // [1, 2]
  • 數組實例的find()和findIndex()方法

數組實例的find方法,用於找出第一個符合條件的數組成員。它的參數是一個回調函數,全部數組成員依次執行該回調函數,直到找出第一個返回值爲true的成員,而後返回該成員。若是沒有符合條件的成員,則返回undefined

[1, 4, -5, 10].find((n) => n < 0)
// -5

數組實例的findIndex方法的用法與find方法很是相似,返回第一個符合條件的數組成員的位置,若是全部成員都不符合條件,則返回-1。

[1, 5, 10, 15].findIndex(function(value, index, arr) {
  return value > 9;
}) // 2
  • 數組實例的fill()

fill方法使用給定值,填充一個數組

['a', 'b', 'c'].fill(7)
// [7, 7, 7]

new Array(3).fill(7)
// [7, 7, 7]

fill方法還能夠接受第二個和第三個參數,用於指定填充的起始位置和結束位置

['a', 'b', 'c'].fill(7, 1, 2)
// ['a', 7, 'c']
  • entries(),keys()和values()

它們都返回一個遍歷器對象,能夠用for...of循環進行遍歷

惟一的區別是keys()是對鍵名的遍歷、values()是對鍵值的遍歷,entries()是對鍵值對的遍歷

for (let index of ['a', 'b'].keys()) {
  console.log(index);
}
// 0
// 1

for (let elem of ['a', 'b'].values()) {
  console.log(elem);
}
// 'a'
// 'b'

for (let [index, elem] of ['a', 'b'].entries()) {
  console.log(index, elem);
}
// 0 "a"
// 1 "b"
  • 數組實例的includes()

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

    該方法的第二個參數表示搜索的起始位置,默認爲0。若是第二個參數爲負數,則表示倒數的位置,若是這時它大於數組長度(好比第二個參數爲-4,但數組長度爲3),則會重置爲從0開始。

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

    indexOf方法有兩個缺點,一是不夠語義化,它的含義是找到參數值的第一個出現位置,因此要去比較是否不等於-1,表達起來不夠直觀。二是,它內部使用嚴格相等運算符(===)進行判斷,這會致使對NaN的誤判

    [NaN].indexOf(NaN) //-1
    [NaN].includes(NaN) //true
  • 數組實例的flat()

將嵌套的數組「拉平」,變成一維的數組。該方法返回一個新數組,對原數據沒有影響

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

[1, 2, [3, [4, 5]]].flat(2)
// [1, 2, 3, 4, 5]
相關文章
相關標籤/搜索