數(shù)組的方法比較

1.filter(返回的是滿足表達(dá)式的項(xiàng),可以return)

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);

// expected output: Array ["exuberant", "destruction", "present"]

1).forEach方法用來(lái)調(diào)用數(shù)組的每個(gè)元素,將元素傳給回調(diào)函數(shù)

2).forEach對(duì)于空數(shù)組是不會(huì)調(diào)用回調(diào)函數(shù)的。 無(wú)論arr是不是空數(shù)組,forEach返回的都是undefined。這個(gè)方法只是將數(shù)組中的每一項(xiàng)作為callback的參數(shù)執(zhí)行一次。

2.forEach(不能return)

const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));

3.map(可以return,可以直接返回想要的數(shù)據(jù), 創(chuàng)建一個(gè)新數(shù)組,其結(jié)果是該數(shù)組中的每個(gè)元素都調(diào)用一次提供的函數(shù)后的返回)

const array1 = [1, 4, 9, 16];

// pass a function to map

const map1 = array1.map(x => x * 2);

console.log(map1);

// expected output: Array [2, 8, 18, 32]

1).map方法返回一個(gè)新的數(shù)組,數(shù)組中的元素為原始數(shù)組調(diào)用函數(shù)處理后的值。

2).map方法不會(huì)對(duì)空數(shù)組進(jìn)行檢測(cè),map方法不會(huì)改變?cè)紨?shù)組。

3). 若arr為空數(shù)組,則map方法返回的也是一個(gè)空數(shù)組。

4.reduce

?const array1 = [1, 2, 3, 4];? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?const reducer = (accumulator, currentValue) => accumulator + currentValue;? ? ? ? ? ? ? ? ? // 1 + 2 + 3 + 4? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?console.log(array1.reduce(reducer));? ? ? //expected output: 10? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?// 5 + 1 + 2 + 3 + 4? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?console.log(array1.reduce(reducer, 5));// expected output: 15?

5.every(檢測(cè)一個(gè)數(shù)組的所有元素是否都能通過(guò)制定函數(shù)的測(cè)試,返回一個(gè)boolean值,空數(shù)組的話會(huì)返回true)

const isBelowThreshold = (currentValue) => currentValue < 40;

const array1 = [1, 30, 39, 29, 10, 13];

console.log(array1.every(isBelowThreshold));// expected output: true?

6.find(返回?cái)?shù)組中滿足提供的測(cè)試函數(shù)的第一個(gè)元素的值)

const array1 = [5, 12, 8, 130, 44];

const found = array1.find(element => element > 10);

console.log(found);

// expected output: 12

7.some(測(cè)試數(shù)組中是不是至少有1個(gè)元素通過(guò)了被提供的函數(shù)測(cè)試。它返回的是一個(gè)Boolean類型的值。)

const array = [1, 2, 3, 4, 5];

// checks whether an element is even

const even = (element) => element % 2 === 0;

console.log(array.some(even));

// expected output: true

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容