JavaScript數(shù)組常用方法find、findIndex、filter、map、flatMap及some詳解
前言
這些數(shù)組方法都是ES6引入的,它們?yōu)樘幚頂?shù)組提供了更簡潔、更函數(shù)式的方式。下面我將詳細介紹每個方法的用法和使用場景,并提供示例。
1. find()
作用:返回數(shù)組中滿足提供的測試函數(shù)的第一個元素的值。如果沒有找到則返回undefined。
使用場景:當你需要從數(shù)組中查找第一個符合條件的元素時。
const users = [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
{ id: 3, name: 'Charlie', age: 35 }
];
// 查找第一個年齡大于30的用戶
const user = users.find(user => user.age > 30);
console.log(user); // { id: 3, name: 'Charlie', age: 35 }
// 查找不存在的用戶
const notFound = users.find(user => user.age > 40);
console.log(notFound); // undefined
2. findIndex()
作用:返回數(shù)組中滿足提供的測試函數(shù)的第一個元素的索引。若沒有找到則返回-1。
使用場景:當你需要知道某個元素在數(shù)組中的位置時。
const numbers = [10, 20, 30, 40, 50]; // 查找第一個大于25的元素的索引 const index = numbers.findIndex(num => num > 25); console.log(index); // 2 // 查找不存在的元素的索引 const notFoundIndex = numbers.findIndex(num => num > 100); console.log(notFoundIndex); // -1
3. filter()
作用:創(chuàng)建一個新數(shù)組,包含通過所提供函數(shù)實現(xiàn)的測試的所有元素。
使用場景:當你需要從數(shù)組中篩選出符合條件的多個元素時。
const products = [
{ id: 1, name: 'Laptop', price: 999, inStock: true },
{ id: 2, name: 'Phone', price: 699, inStock: false },
{ id: 3, name: 'Tablet', price: 499, inStock: true }
];
// 篩選有庫存的產(chǎn)品
const availableProducts = products.filter(product => product.inStock);
console.log(availableProducts);
// [
// { id: 1, name: 'Laptop', price: 999, inStock: true },
// { id: 3, name: 'Tablet', price: 499, inStock: true }
// ]
// 篩選價格低于500的產(chǎn)品
const cheapProducts = products.filter(product => product.price < 500);
console.log(cheapProducts);
// [{ id: 3, name: 'Tablet', price: 499, inStock: true }]
4. map()
作用:創(chuàng)建一個新數(shù)組,其結(jié)果是該數(shù)組中的每個元素都調(diào)用一個提供的函數(shù)后的返回值。
使用場景:當你需要對數(shù)組中的每個元素進行轉(zhuǎn)換時。
const numbers = [1, 2, 3, 4];
// 將每個數(shù)字平方
const squares = numbers.map(num => num * num);
console.log(squares); // [1, 4, 9, 16]
// 從對象數(shù)組中提取特定屬性
const names = users.map(user => user.name);
console.log(names); // ['Alice', 'Bob', 'Charlie']
// 添加新屬性
const usersWithStatus = users.map(user => ({
...user,
status: user.age > 30 ? 'Senior' : 'Junior'
}));
console.log(usersWithStatus);
// [
// { id: 1, name: 'Alice', age: 25, status: 'Junior' },
// { id: 2, name: 'Bob', age: 30, status: 'Junior' },
// { id: 3, name: 'Charlie', age: 35, status: 'Senior' }
// ]
5. flatMap()
作用:首先使用映射函數(shù)映射每個元素,然后將結(jié)果壓縮成一個新數(shù)組。相當于先map()再flat(1)。
使用場景:當你需要先映射然后扁平化結(jié)果時。
const sentences = ["Hello world", "Good morning", "Have a nice day"];
// 將句子拆分為單詞并扁平化
const words = sentences.flatMap(sentence => sentence.split(' '));
console.log(words);
// ['Hello', 'world', 'Good', 'morning', 'Have', 'a', 'nice', 'day']
// 傳統(tǒng)方式需要先map再flat
const wordsOldWay = sentences.map(sentence => sentence.split(' ')).flat();
console.log(wordsOldWay); // 同上
// 處理嵌套數(shù)組
const data = [[1], [2, 3], [4]];
const flattened = data.flatMap(arr => arr.map(x => x * 2));
console.log(flattened); // [2, 4, 6, 8]
6. some()
作用:測試數(shù)組中是否至少有一個元素通過了提供的函數(shù)的測試。返回布爾值。
使用場景:當你需要檢查數(shù)組中是否有元素滿足某個條件時。
const numbers = [1, 2, 3, 4, 5];
// 檢查是否有偶數(shù)
const hasEven = numbers.some(num => num % 2 === 0);
console.log(hasEven); // true
// 檢查是否有大于10的數(shù)
const hasLargeNumber = numbers.some(num => num > 10);
console.log(hasLargeNumber); // false
// 檢查用戶列表中是否有管理員
const users = [
{ id: 1, name: 'Alice', isAdmin: false },
{ id: 2, name: 'Bob', isAdmin: true },
{ id: 3, name: 'Charlie', isAdmin: false }
];
const hasAdmin = users.some(user => user.isAdmin);
console.log(hasAdmin); // true
一、查詢類方法
1.includes()
檢查數(shù)組是否包含某個值,返回布爾值
[1, 2, 3].includes(2); // true
['a', 'b', 'c'].includes('d'); // false
2.indexOf() / lastIndexOf()
返回元素在數(shù)組中的第一個/最后一個索引,找不到返回-1
['a', 'b', 'c', 'b'].indexOf('b'); // 1
['a', 'b', 'c', 'b'].lastIndexOf('b'); // 3
3.every()
檢查是否所有元素都滿足條件
[12, 5, 8, 130, 44].every(x => x >= 10); // false [12, 54, 18, 130, 44].every(x => x >= 10); // true
二、操作類方法
1.concat()
合并兩個或多個數(shù)組
[1, 2].concat([3, 4], [5, 6]); // [1, 2, 3, 4, 5, 6]
2.slice()
返回數(shù)組的淺拷貝部分
['a', 'b', 'c', 'd'].slice(1, 3); // ['b', 'c']
3.splice()
修改數(shù)組內(nèi)容(添加/刪除元素)
const arr = [1, 2, 3, 4]; arr.splice(1, 2, 'a', 'b'); // 返回 [2, 3] console.log(arr); // [1, 'a', 'b', 4]
三、轉(zhuǎn)換類方法
1.join()
將數(shù)組元素連接成字符串
['Fire', 'Air', 'Water'].join(); // "Fire,Air,Water"
['Fire', 'Air', 'Water'].join('-'); // "Fire-Air-Water"
2. reduce() / reduceRight()
對數(shù)組元素執(zhí)行累加器函數(shù)
[1, 2, 3, 4].reduce((acc, val) => acc + val); // 10 [1, 2, 3, 4].reduce((acc, val) => acc + val, 5); // 15 (帶初始值)
四、排序類方法
1.sort()
對數(shù)組元素進行排序(原地修改)
const fruits = ['banana', 'apple', 'pear']; fruits.sort(); // ['apple', 'banana', 'pear'] const numbers = [4, 2, 5, 1, 3]; numbers.sort((a, b) => a - b); // [1, 2, 3, 4, 5]
2. reverse()
反轉(zhuǎn)數(shù)組順序(原地修改)
['a', 'b', 'c'].reverse(); // ['c', 'b', 'a']
五、迭代類方法
1. forEach()
對每個數(shù)組元素執(zhí)行函數(shù)
['a', 'b', 'c'].forEach((item, index) => {
console.log(`${index}: ${item}`);
});
// 0: a
// 1: b
// 2: c
六、新增元素方法
1.push() / pop()
在數(shù)組末尾添加/刪除元素
const arr = [1, 2]; arr.push(3); // 返回新長度3,arr變?yōu)閇1, 2, 3] arr.pop(); // 返回3,arr變回[1, 2]
2.unshift() / shift()
在數(shù)組開頭添加/刪除元素
const arr = [1, 2]; arr.unshift(0); // 返回新長度3,arr變?yōu)閇0, 1, 2] arr.shift(); // 返回0,arr變回[1, 2]
七、ES6+新增方法
1. flat()
將嵌套數(shù)組扁平化
[1, 2, [3, 4]].flat(); // [1, 2, 3, 4] [1, 2, [3, [4, 5]]].flat(2); // [1, 2, 3, 4, 5]
2. fill()
用固定值填充數(shù)組
[1, 2, 3].fill(0); // [0, 0, 0] [1, 2, 3, 4].fill(5, 1, 3); // [1, 5, 5, 4]
3. Array.from()
從類數(shù)組對象創(chuàng)建新數(shù)組
Array.from('foo'); // ['f', 'o', 'o']
Array.from([1, 2, 3], x => x + x); // [2, 4, 6]
總結(jié)對比
| 方法 | 返回值 | 是否修改原數(shù)組 | 使用場景 |
|---|---|---|---|
| concat() | 新數(shù)組 | 否 | 合并數(shù)組 |
| every() | 布爾值 | 否 | 檢查所有元素是否滿足條件 |
| fill() | 修改后的數(shù)組 | 是 | 填充數(shù)組元素 |
| filter() | 新數(shù)組 | 否 | 篩選元素 |
| find() | 第一個匹配元素或undefined | 否 | 查找單個元素 |
| findIndex() | 索引或-1 | 否 | 查找元素位置 |
| flat() | 新數(shù)組 | 否 | 扁平化嵌套數(shù)組 |
| flatMap() | 新數(shù)組 | 否 | 映射后扁平化 |
| forEach() | undefined | 否 | 遍歷數(shù)組 |
| includes() | 布爾值 | 否 | 檢查是否包含值 |
| indexOf() | 索引或-1 | 否 | 查找元素首次出現(xiàn)位置 |
| join() | 字符串 | 否 | 連接數(shù)組為字符串 |
| map() | 新數(shù)組 | 否 | 轉(zhuǎn)換每個元素 |
| pop() | 刪除的元素 | 是 | 移除最后一個元素 |
| push() | 新長度 | 是 | 末尾添加元素 |
| reduce() | 累加結(jié)果 | 否 | 累加計算 |
| reverse() | 反轉(zhuǎn)后的數(shù)組 | 是 | 反轉(zhuǎn)數(shù)組順序 |
| shift() | 刪除的元素 | 是 | 移除第一個元素 |
| slice() | 新數(shù)組 | 否 | 截取數(shù)組部分 |
| some() | 布爾值 | 否 | 檢查是否有元素滿足條件 |
| sort() | 排序后的數(shù)組 | 是 | 數(shù)組排序 |
| splice() | 刪除的元素數(shù)組 | 是 | 添加/刪除元素 |
| unshift() | 新長度 | 是 | 開頭添加元素 |
這些方法都遵循函數(shù)式編程的原則,不會修改原數(shù)組,而是返回新數(shù)組或值。它們可以鏈式調(diào)用,使得代碼更加簡潔和可讀。
到此這篇關(guān)于JavaScript數(shù)組常用方法find、findIndex、filter、map、flatMap及some的文章就介紹到這了,更多相關(guān)JS數(shù)組常用方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- JS中filter( )數(shù)組過濾器的使用
- JavaScript遍歷數(shù)組的三種方法map、forEach與filter實例詳解
- JavaScript 數(shù)組some()和filter()的用法及區(qū)別
- JavaScript中find()、findIndex()、filter()、indexOf()處理數(shù)組方法的具體區(qū)別詳解
- js 數(shù)組 find,some,filter,reduce區(qū)別詳解
- JS中的常見數(shù)組遍歷案例詳解(forEach,?map,?filter,?sort,?reduce,?every)
- JavaScript 數(shù)組的常用方法find 和 filter詳解及區(qū)別介紹
- JavaScript數(shù)組方法push()、forEach()、filter()、sort()實戰(zhàn)教程
相關(guān)文章
JavaScript中的await函數(shù)使用小結(jié)
async 函數(shù)是 AsyncFunction 構(gòu)造函數(shù)的實例,并且其中允許使用 await 關(guān)鍵字,async 和 await 關(guān)鍵字讓我們可以用一種更簡潔的方式寫出基于 Promise 的異步行為,而無需刻意地鏈式調(diào)用 promise,這篇文章主要介紹了JavaScript中的await,需要的朋友可以參考下2024-01-01
javascript 循環(huán)調(diào)用示例介紹
循環(huán)調(diào)用,如果已經(jīng)獲取到了結(jié)果,則退出循環(huán),下面有個不錯的示例,感興趣的朋友可以嘗試操作下2013-11-11
JavaScript如何實現(xiàn)數(shù)組內(nèi)的值累加
我們會經(jīng)常在開發(fā)過程中,需要獲取數(shù)組中的值累加,所以下面這篇文章主要給大家介紹了關(guān)于JavaScript如何實現(xiàn)數(shù)組內(nèi)的值累加的相關(guān)資料,文中給出了詳細的代碼示例,需要的朋友可以參考下2023-11-11

