JavaScript學(xué)習(xí)筆記之ES6數(shù)組方法
來(lái)源:易賢網(wǎng) 閱讀:881 次 日期:2016-07-15 16:57:13
溫馨提示:易賢網(wǎng)小編為您整理了“JavaScript學(xué)習(xí)筆記之ES6數(shù)組方法”,方便廣大網(wǎng)友查閱!

ES6(ECMAScript 6)是即將到來(lái)的新版本JavaScript語(yǔ)言的標(biāo)準(zhǔn),代號(hào)harmony(和諧之意,顯然沒有跟上我國(guó)的步伐,我們已經(jīng)進(jìn)入中國(guó)夢(mèng)版本了)。上一次標(biāo)準(zhǔn)的制訂還是2009年出臺(tái)的ES5。目前ES6的標(biāo)準(zhǔn)化工作正在進(jìn)行中,預(yù)計(jì)會(huì)在14年12月份放出正式敲定的版本。但大部分標(biāo)準(zhǔn)已經(jīng)就緒,且各瀏覽器對(duì)ES6的支持也正在實(shí)現(xiàn)中。

ES6給數(shù)組添加了一些新特性,而這些新特性到目前為止完全可以運(yùn)用到自己的業(yè)務(wù)層。在這一節(jié)中將總結(jié)有關(guān)于ES6給數(shù)組提供一些新特性的使用方法。

ES6提供的兩個(gè)靜態(tài)方法:

Array.from

Array.of

ES6提供操作、填充和過(guò)濾數(shù)組的方法:

Array.prototype.copyWidthin

Array.prototype.fill

Array.prototype.find

Array.prototype.findIndex

ES6中有關(guān)于數(shù)組迭代的方法:

Array.prototype.keys

Array.prototype.values

Array.prototype.entries

Array.prototype[Symbol.iterator]

接下來(lái)主要看看這些方法的使用。

Array.from()

Array.from()方法主要用于將兩類對(duì)象(類似數(shù)組的對(duì)象[array-like object]和可遍歷對(duì)象[iterable])轉(zhuǎn)為真正的數(shù)組。

在ES5中常常使用下面這樣的方法將一個(gè)類似數(shù)組的對(duì)象轉(zhuǎn)換成一個(gè)數(shù)組:

function cast () {

return Array.prototype.slice.call(arguments);

}

cast('a','b','c','d'); // ["a", "b", "c", "d"]

或者你也可以寫成:

function cast () {

return [].slice.call(arguments);

}

cast('a','b','c','d'); // ["a", "b", "c", "d"]

在ES6中可以使用Array.from將一個(gè)類似數(shù)組的對(duì)象轉(zhuǎn)換為一個(gè)真正的數(shù)組。

所謂類似數(shù)組的對(duì)象,本質(zhì)特征只有一點(diǎn),即必須有l(wèi)ength屬性。因此,任何有l(wèi)ength屬性的對(duì)象都是類似數(shù)組對(duì)象,都可以通過(guò)Array.from方法將其轉(zhuǎn)換成一個(gè)真正的數(shù)組。

let arrayLike = {

'0': 'a',

'1': 'b',

'2': 'c',

length: 3

}

console.log(Array.from(arrayLike)); // ["a","b","c"]

在ES6中,擴(kuò)展運(yùn)算符(...)也可以將某些數(shù)據(jù)結(jié)構(gòu)轉(zhuǎn)為數(shù)組。只不過(guò)它需要在背后調(diào)用遍歷器接口Symbol.iterator。

function cast (){

return [...arguments]

}

cast('a','b','c'); // ["a","b","c"]

值得注意的是如果一個(gè)對(duì)象沒有部署遍歷器接口,使用擴(kuò)展運(yùn)算符是無(wú)法將類似數(shù)組對(duì)象轉(zhuǎn)換成數(shù)組。

Array.from接受三個(gè)參數(shù),但只有input是必須的:

input: 你想要轉(zhuǎn)換的類似數(shù)組對(duì)象和可遍歷對(duì)象

map: 類似于數(shù)組的map方法,用來(lái)對(duì)每個(gè)元素進(jìn)行處理,將處理后的值放入返回的數(shù)組

context: 綁定map中用到的this

只要是部署了iterator接口的數(shù)據(jù)結(jié)構(gòu),Array.from都能將其轉(zhuǎn)為數(shù)組:

let arr = Array.from('w3cplus.com')

console.log(arr); // ["w","3","c","p","l","u","s",".","c","o","m"]

let namesSet = new Set(['a', 'b'])

let arr2 = Array.from(namesSet) 

console.log(arr2); //["a","b"]

上面的代碼,因?yàn)樽址麉魏蚐et結(jié)構(gòu)都具有iterator接口,因此可以被Array.from轉(zhuǎn)為真正的數(shù)組。如果參數(shù)是一個(gè)真正的數(shù)組,Array.from也會(huì)返回一個(gè)一模一樣的新數(shù)組:

let arr = Array.from([1, 2, 3]);

console.log(arr); // [1,2,3]

前面也說(shuō)過(guò)Array.from還可以接受第二個(gè)參數(shù),作用類似于數(shù)組的map方法,用來(lái)對(duì)每個(gè)元素進(jìn)行處理,處理后的值放入返回的數(shù)組:

Array.from(arrayLike, x => x * x);

// 等同于

Array.from(arrayLike).map(x => x * x);

Array.from([1, 2, 3], (x) => x * x)

// [1, 4, 9]

如果map函數(shù)里面用到了this關(guān)鍵字,還可以傳入Array.from的第三個(gè)參數(shù),用來(lái)綁定this。

Array.from()可以將各種值轉(zhuǎn)為真正的數(shù)組,并且還提供map功能。這實(shí)際上意味著,只要有一個(gè)原始的數(shù)據(jù)結(jié)構(gòu),你就可以先對(duì)它的值進(jìn)行處理,然后轉(zhuǎn)成規(guī)范的數(shù)組結(jié)構(gòu),進(jìn)而就可以使用數(shù)量眾多的數(shù)組方法。

Array.from({ length: 2 }, () => 'jack')

// ['jack', 'jack']

上面代碼中,Array.from的第一個(gè)參數(shù)指定了第二個(gè)參數(shù)運(yùn)行的次數(shù)。這種特性可以讓該方法的用法變得非常靈活。

Array.from()的另一個(gè)應(yīng)用是,將字符串轉(zhuǎn)為數(shù)組,然后返回字符串的長(zhǎng)度。因?yàn)樗苷_處理各種Unicode字符,可以避免JavaScript將大于\uFFFF的Unicode字符,算作兩個(gè)字符的bug。

function countSymbols(string) {

return Array.from(string).length;

}

使用Array.from()還可以返回各種數(shù)據(jù)類型:

function typesOf () {

return Array.from(arguments, value => typeof value)

}

typesOf(null, [], NaN)

// <- ['object', 'object', 'number']

你也可以使用map方法實(shí)現(xiàn)上面代碼的功能:

function typesOf (...all) {

return all.map(value => typeof value)

}

typesOf(null, [], NaN)

// <- ['object', 'object', 'number']

Array.of

使用Array.of方法可以將一組值轉(zhuǎn)換為數(shù)組。

Array.of = function of () {

return Array.prototype.slice.call(arguments)

}

但你不能使用Array.of來(lái)替代Array.prototype.slice.call,他們的行為不一樣:

Array.prototype.slice.call([1, 2, 3])

// <- [1, 2, 3]

Array.of(1, 2, 3)

// <- [1, 2, 3]

Array.of(3)

// <- [1]

這個(gè)方法主要目的主要還是用來(lái)彌補(bǔ)數(shù)組構(gòu)造函數(shù)Array()的不足,因?yàn)閰?shù)個(gè)數(shù)的不同,會(huì)導(dǎo)致Array()行為有所差異:

new Array()

// <- []

new Array(undefined)

// <- [undefined]

new Array(1)

// <- [undefined x 1]

new Array(3)

// <- [undefined x 3]

new Array(1, 2)

// <- [1, 2]

new Array(-1)

// <- RangeError: Invalid array length

Array.of基本上可以用來(lái)替代Array()或new Array(),并且不存在由于參數(shù)不同而導(dǎo)致的重載,而且他們的行為非常統(tǒng)一:

Array.of()

// <- []

Array.of(undefined)

// <- [undefined]

Array.of(1)

// <- [1]

Array.of(3)

// <- [3]

Array.of(1, 2)

// <- [1, 2]

Array.of(-1)

// <- [-1]

Array.of方法可以使用下面的代碼來(lái)模擬實(shí)現(xiàn):

function ArrayOf(){

return [].slice.call(arguments);

}

copyWidthin

copyWidthin方法可以在當(dāng)前數(shù)組內(nèi)部,將指定位置的數(shù)組項(xiàng)復(fù)制到其他位置(會(huì)覆蓋原數(shù)組項(xiàng)),然后返回當(dāng)前數(shù)組。使用copyWidthin方法會(huì)修改當(dāng)前數(shù)組。

Array.prototype.copyWithin(target, start = 0, end = this.length)

copyWidthin將會(huì)接受三個(gè)參數(shù):

target: 這個(gè)參數(shù)是必須的,從該位置開始替換數(shù)組項(xiàng)

start: 這是一個(gè)可選參數(shù),從該位置開始讀取數(shù)組項(xiàng),默認(rèn)為0,如果為負(fù)值,表示從數(shù)組的右邊向左開始讀取

end: 這是一個(gè)可選參數(shù),到該位置停止讀取的數(shù)組項(xiàng),默認(rèn)等于Array.length。如果為負(fù)值,表示倒數(shù)

我們先來(lái)看一個(gè)簡(jiǎn)單的示例,下面聲明了一個(gè)items數(shù)組:

var items = [1, 2, 3, ,,,,,,,]; // <- [1, 2, 3, undefined x 7]

下面的代碼將在數(shù)組items的第六個(gè)位置開始粘貼數(shù)組項(xiàng)。粘貼過(guò)去的數(shù)組項(xiàng)是從items的第二位開始到第三位置結(jié)束。

items.copyWithin(6, 1, 3)

// <- [1, 2, 3, undefined × 3, 2, 3, undefined × 2]

下面是更多例子:

// 將3號(hào)位復(fù)制到0號(hào)位

[1, 2, 3, 4, 5].copyWithin(0, 3, 4)

// [4, 2, 3, 4, 5]

// -2相當(dāng)于3號(hào)位,-1相當(dāng)于4號(hào)位

[1, 2, 3, 4, 5].copyWithin(0, -2, -1)

// [4, 2, 3, 4, 5]

// 將3號(hào)位復(fù)制到0號(hào)位

[].copyWithin.call({length: 5, 3: 1}, 0, 3)

// {0: 1, 3: 1, length: 5}

// 將2號(hào)位到數(shù)組結(jié)束,復(fù)制到0號(hào)位

var i32a = new Int32Array([1, 2, 3, 4, 5]);

i32a.copyWithin(0, 2);

// Int32Array [3, 4, 5, 4, 5]

// 對(duì)于沒有部署TypedArray的copyWithin方法的平臺(tái)

// 需要采用下面的寫法

[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4);

// Int32Array [4, 2, 3, 4, 5]

Array.prototype.fill

Array.prototype.fill方法使用給定的值填充一個(gè)數(shù)組:

['a', 'b', 'c'].fill(0)

// <- [0, 0, 0]

new Array(3).fill(0)

// <- [0, 0, 0]

上面這種方法用于空數(shù)組的初始化非常方便。數(shù)組中已有的元素會(huì)全部被抹去。

除此之外,Array.prototype.fill方法還可以接受第二個(gè)和第三個(gè)參數(shù),用于指定填充的起始位置和結(jié)束位置。

['a', 'b', 'c',,,].fill(0, 2)

// <- ['a', 'b', 0, 0, 0]

new Array(5).fill(0, 0, 3)

// <- [0, 0, 0, undefined x 2]

Array.prototype.fill提供的值可以是任意的,不僅可以是一個(gè)數(shù)值,甚至還可以是一個(gè)原始類型:

new Array(3).fill({})

// <- [{}, {}, {}]

不過(guò)這個(gè)方法不可以接受數(shù)組的映射方法,不過(guò)可以接受一個(gè)索引參數(shù)或類似下面這樣的方式:

new Array(3).fill(function foo () {})

// <- [function foo () {}, function foo () {}, function foo () {}]

Array.prototype.find

Array.prototype.find方法用于找出第一個(gè)符合條件的數(shù)組成員。它的參數(shù)是一個(gè)回調(diào)函數(shù),所有數(shù)組成員依次執(zhí)行該回調(diào)函數(shù),直到找出第一個(gè)返回值為true的數(shù)組項(xiàng),然后返回該數(shù)組項(xiàng)。如果沒有符合條件的數(shù)組項(xiàng),則返回undefined。

[1, 2, 3, 4, 5].find(item => item > 2)

// <- 3

[1, 2, 3, 4, 5].find((item, i) => i === 3)

// <- 4

[1, 2, 3, 4, 5].find(item => item === Infinity)

// <- undefined

另外這種方法的回調(diào)函數(shù)可以接受三個(gè)參數(shù),依次為當(dāng)前的值、當(dāng)前的位置和原始數(shù)組。

[1, 5, 10, 15].find(function(value, index, arr) {

return value > 9;

}) // 10

Array.prototype.findIndex

這個(gè)方法類似于.some和.find方法。像.some返回true;像.find返回item。如果array[index] === item則返回其index。

Array.prototype.findIndex方法主要是用來(lái)返回?cái)?shù)組項(xiàng)在數(shù)組中的位置。其和Array.prototype.find方法非常類似,接受一個(gè)回調(diào)函數(shù),如果符合回調(diào)函數(shù)的條件,則返回?cái)?shù)組項(xiàng)在數(shù)組中的位置,如果所有數(shù)組項(xiàng)都不符合回調(diào)函數(shù)條件,則會(huì)返回-1。

[1, 2, 3, 4, 5].find(item => item > 2)

// <- 2

[1, 2, 3, 4, 5].find((item, i) => i === 3)

// <- 3

[1, 2, 3, 4, 5].find(item => item === Infinity)

// <- -1

這個(gè)方法也可以接受第二個(gè)參數(shù),用來(lái)綁定回調(diào)函數(shù)的this對(duì)象。

注:Array.prototype.find和Array.prototype.findIndex兩個(gè)方法都可以發(fā)現(xiàn)NaN,彌補(bǔ)數(shù)組的indexOf方法的不足。

[NaN].indexOf(NaN)

// -1

[NaN].findIndex(y => Object.is(NaN, y))

// 0

上面的代碼中,indexOf方法無(wú)法識(shí)別數(shù)組的NaN成員,但是findIndex方法可以借助Object.is方法做到。

ES6遍歷數(shù)組的方法

ES6提供了三個(gè)新方法:entries()、keys()和values(),用來(lái)遍歷數(shù)組。它們都返回一個(gè)遍歷器對(duì)象,可以用for...of循環(huán)進(jìn)行遍歷,唯一的區(qū)別是keys()是對(duì)數(shù)組的鍵名的遍歷、values()是對(duì)數(shù)組鍵值的遍歷,entries()方法是對(duì)數(shù)值的鍵值對(duì)的遍歷。

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"

如果不使用for...of循環(huán),可以手動(dòng)調(diào)用遍歷器對(duì)象的next方法,進(jìn)行遍歷:

let letter = ['a', 'b', 'c'];

let entries = letter.entries();

console.log(entries.next().value); // [0, 'a']

console.log(entries.next().value); // [1, 'b']

console.log(entries.next().value); // [2, 'c']

總結(jié)

這里簡(jiǎn)單的總結(jié)了有關(guān)于ES6中數(shù)組的相關(guān)方法。說(shuō)實(shí)在的,初次接觸ES6,很多東西都看得云里來(lái)霧里去。這里只是整理了一下這方面的相關(guān)知識(shí)。

關(guān)于JavaScript學(xué)習(xí)筆記之ES6數(shù)組方法小編就給大家介紹到這里,希望對(duì)大家有所幫助!

更多信息請(qǐng)查看網(wǎng)絡(luò)編程
易賢網(wǎng)手機(jī)網(wǎng)站地址:JavaScript學(xué)習(xí)筆記之ES6數(shù)組方法
由于各方面情況的不斷調(diào)整與變化,易賢網(wǎng)提供的所有考試信息和咨詢回復(fù)僅供參考,敬請(qǐng)考生以權(quán)威部門公布的正式信息和咨詢?yōu)闇?zhǔn)!

2025國(guó)考·省考課程試聽報(bào)名

  • 報(bào)班類型
  • 姓名
  • 手機(jī)號(hào)
  • 驗(yàn)證碼
關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡(jiǎn)要咨詢 | 簡(jiǎn)要咨詢須知 | 新媒體/短視頻平臺(tái) | 手機(jī)站點(diǎn) | 投訴建議
工業(yè)和信息化部備案號(hào):滇ICP備2023014141號(hào)-1 云南省教育廳備案號(hào):云教ICP備0901021 滇公網(wǎng)安備53010202001879號(hào) 人力資源服務(wù)許可證:(云)人服證字(2023)第0102001523號(hào)
云南網(wǎng)警備案專用圖標(biāo)
聯(lián)系電話:0871-65099533/13759567129 獲取招聘考試信息及咨詢關(guān)注公眾號(hào):hfpxwx
咨詢QQ:1093837350(9:00—18:00)版權(quán)所有:易賢網(wǎng)
云南網(wǎng)警報(bào)警專用圖標(biāo)