六個(gè)ES6中很酷的數(shù)組函數(shù)
1、Array .of
關(guān)于奇怪的 Array 函數(shù),眾所周知,我們可以通過Array函數(shù)做以下事情。
初始化指定長(zhǎng)度的數(shù)組;設(shè)置數(shù)組的初始值。
// 1. Initialize an array of the specified length
const array1 = Array(3) // [ , , ]
// 2. Set the initial value of the array
const array2 = Array() // []
const array3 = Array(undefined) // [ undefined ]
const array4 = Array(1, 2, 3) // [ 1, 2, 3 ]
傳遞給Array函數(shù)的參數(shù)個(gè)數(shù)不一樣,其作用也不一樣。這常常讓我感到困惑。
幸運(yùn)的是,我們可以使用 Array.of 來彌補(bǔ) Array 的不足。
// it's not initializing an array of length 3
const array1 = Array.of(3) // [ 3 ]
const array2 = Array.of() // []
const array3 = Array.of(undefined) // [ undefined ]
const array4 = Array.of(1, 2, 3) // [ 1, 2, 3 ]
2、 Array.from
from 方法中,我們可以通過 Array.from 方法將類數(shù)組對(duì)象、arguments 對(duì)象、NodeList 對(duì)象轉(zhuǎn)換為真正的數(shù)組。
1)、類數(shù)組對(duì)象
const arrayLike = {
0: 'fatfish',
1: 'medium',
length: 2
}
const array1 = [].slice.call(arrayLike) // ['fatfish', 'medium']
// A more convenient way
const array2 = Array.from(arrayLike) // ['fatfish', 'medium']
2)、節(jié)點(diǎn)列表
const domsNodeList = document.querySelectorAll('div')
const domsArray = Array.from(domsNodeList) // [ dom, dom, dom, ... ]
3)、 Arguments
const logInfo = function () {
console.log('arguments', arguments)
console.log('Array.from arguments', Array.from(arguments))
}
logInfo('fatfish', 100)
logInfo('fatfish')
4)、Array.from的第二個(gè)參數(shù)
我們可以使用 Array.from 方法,如“[].map”。
const array = [ 1, 2, 3 ]
const array2 = array.map((num) => num * 2) // [2, 4, 6]
const array3 = Array.from(array, (num) => num * 2) // [2, 4, 6]
3、 includes
當(dāng)滿足其中一個(gè)條件時(shí),我們經(jīng)常會(huì)寫這樣的判斷語句來做某事。
const num = 1
if (num === 1 || num === 2 || num === 3 || num === 4) {
console.log(num) // 1
}
其實(shí)可以通過include方法來簡(jiǎn)化代碼。
const nums = [ 1, 2, 3, 4 ]
const num = 1
if (nums.includes(num)) {
console.log(num) // 1
}
4、使用“at方法”讀取數(shù)組的尾部元素
你如何讀取數(shù)組的尾部元素?是的,我們需要以“array.length-1”作為下標(biāo)來讀取。
const array = [ 1, 2, 3, 4, 5 ]
const lastEle = array[ array.length - 1 ] // 5
// You can't read like that
const lastEle = array[ - 1 ] // undefined
還有其他方法嗎?
是的,“at”方法將成為您的魔法。當(dāng)然,您也可以讀取數(shù)組中其他位置的元素。
const array = [ 1, 2, 3, 4, 5 ]
const lastEle = array.at(-1) // 5
const ele1 = array.at(0) // 1
5、 flat
flat() 方法創(chuàng)建一個(gè)新數(shù)組,其中所有子數(shù)組元素遞歸連接到指定深度。
const array = [ 1, [ 2, [ 3, [ 4, [ 5 ] ] ] ] ]
// The default depth is 1
const flat1 = array.flat() // [ 1, 2, [ 3, [ 4, [ 5 ] ] ] ]
const flat2 = array.flat(2) // [ 1, 2, 3, [ 4, [ 5 ] ] ]
const flatAll = array.flat(Infinity) // [ 1, 2, 3, 4, 5 ]
6、 findIndex
“findIndex() 方法返回?cái)?shù)組中滿足提供的測(cè)試函數(shù)的第一個(gè)元素的索引。否則,它返回 -1,表示沒有元素通過測(cè)試?!?/p>
const array = [ -1, 0, 10, 10, 20, 100 ]
const index1 = array.findIndex((num) => num < 0) // 0
const index2 = array.findIndex((num) => num >= 10) // 2
最后
以上就是我今天跟你分享的6個(gè)關(guān)于ES6中的數(shù)組函數(shù),如果你覺得有用的話,請(qǐng)記得點(diǎn)贊我,關(guān)注我,并將它分享給你身邊做開發(fā)的朋友,也許能夠幫助到他。