偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

七個 JavaScript 數(shù)組方法,代碼簡潔度提升 80%

開發(fā) 前端
善用數(shù)組方法能極大地簡化代碼,提高代碼運(yùn)行速度和可讀性,分享下用得比較多的7個數(shù)組方法。

善用數(shù)組方法能極大地簡化代碼,提高代碼運(yùn)行速度和可讀性,分享下用得比較多的七個數(shù)組方法。

1. map() - 數(shù)組變形的利器

map()方法創(chuàng)建一個新數(shù)組,其結(jié)果是對原數(shù)組中的每個元素調(diào)用提供的函數(shù)。

// 基礎(chǔ)用法
const numbers = [1, 2, 3, 4];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8]

// 實(shí)際應(yīng)用:處理API返回?cái)?shù)據(jù)
const users = [
    { id: 1, name: 'John', age: 30 },
    { id: 2, name: 'Jane', age: 25 }
];
const userNames = users.map(user => user.name);
console.log(userNames); // ['John', 'Jane']

// 鏈?zhǔn)秸{(diào)用
const prices = [99.99, 199.99, 299.99];
const formattedPrices = prices
    .map(price => price * 0.8) // 打八折
    .map(price => price.toFixed(2)); // 格式化
console.log(formattedPrices); // ['79.99', '159.99', '239.99']

2. filter() - 數(shù)據(jù)篩選神器

filter()方法創(chuàng)建一個新數(shù)組,其中包含通過所提供函數(shù)測試的所有元素。

// 基礎(chǔ)用法
const scores = [65, 90, 75, 85, 55];
const passingScores = scores.filter(score => score >= 60);
console.log(passingScores); // [65, 90, 75, 85]

// 實(shí)際應(yīng)用:復(fù)雜條件過濾
const products = [
    { name: 'Phone', price: 999, inStock: true },
    { name: 'Laptop', price: 1999, inStock: false },
    { name: 'Tablet', price: 499, inStock: true }
];
const availableProducts = products.filter(
    product => product.inStock && product.price < 1000
);
console.log(availableProducts); // [{ name: 'Phone'... }, { name: 'Tablet'... }]

3. reduce() - 數(shù)據(jù)歸并專家

reduce()方法將數(shù)組縮減為單個值,是最強(qiáng)大但也最容易被誤解的方法。

// 基礎(chǔ)用法:求和
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((acc, cur) => acc + cur, 0);
console.log(sum); // 15

// 高級應(yīng)用:數(shù)據(jù)分組
const orders = [
    { product: 'A', category: 'Electronics', price: 100 },
    { product: 'B', category: 'Books', price: 50 },
    { product: 'C', category: 'Electronics', price: 200 }
];

const groupedByCategory = orders.reduce((acc, cur) => {
    acc[cur.category] = acc[cur.category] || [];
    acc[cur.category].push(cur);
    return acc;
}, {});

console.log(groupedByCategory);
// {
//     Electronics: [{ product: 'A'... }, { product: 'C'... }],
//     Books: [{ product: 'B'... }]
// }

4. forEach() - 最常用的遍歷方法

forEach()方法對數(shù)組的每個元素執(zhí)行一次給定的函數(shù),是最直觀的遍歷方法。

// 基礎(chǔ)用法
const items = ['apple', 'banana', 'orange'];
items.forEach((item, index) => {
    console.log(`${index + 1}: ${item}`);
});
// 1: apple
// 2: banana
// 3: orange

// 實(shí)際應(yīng)用:DOM操作
const buttons = document.querySelectorAll('button');
buttons.forEach(button => {
    button.addEventListener('click', () => {
        console.log('Button clicked');
    });
});

// 累加計(jì)算
let total = 0;
const prices = [29.99, 39.99, 49.99];
prices.forEach(price => {
    total += price;
});
console.log(total.toFixed(2)); // '119.97'

5. find() - 精確查找好幫手

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

// 基礎(chǔ)用法
const users = [
    { id: 1, name: 'John' },
    { id: 2, name: 'Jane' },
    { id: 3, name: 'Bob' }
];
const user = users.find(user => user.id === 2);
console.log(user); // { id: 2, name: 'Jane' }

// 實(shí)際應(yīng)用:狀態(tài)查找
const tasks = [
    { id: 1, status: 'pending' },
    { id: 2, status: 'completed' },
    { id: 3, status: 'pending' }
];
const completedTask = tasks.find(task => task.status === 'completed');
console.log(completedTask); // { id: 2, status: 'completed' }

6. some() - 條件判斷利器

some()方法測試數(shù)組中是否至少有一個元素通過了提供的函數(shù)測試。

// 基礎(chǔ)用法
const numbers = [1, 2, 3, 4, 5];
const hasEven = numbers.some(num => num % 2 === 0);
console.log(hasEven); // true

// 實(shí)際應(yīng)用:權(quán)限檢查
const userRoles = ['user', 'editor', 'viewer'];
const canEdit = userRoles.some(role => role === 'editor');
console.log(canEdit); // true

// 復(fù)雜條件檢查
const products = [
    { name: 'Phone', price: 999 },
    { name: 'Laptop', price: 1999 },
    { name: 'Tablet', price: 499 }
];
const hasAffordableProduct = products.some(
    product => product.price < 500
);
console.log(hasAffordableProduct); // true

7. every() - 全員檢查神器

every()方法測試數(shù)組的所有元素是否都通過了提供的函數(shù)測試。

// 基礎(chǔ)用法
const scores = [90, 85, 95, 100];
const allPassed = scores.every(score => score >= 60);
console.log(allPassed); // true

// 實(shí)際應(yīng)用:表單驗(yàn)證
const formFields = [
    { value: 'John', required: true },
    { value: 'john@example.com', required: true },
    { value: '123456', required: true }
];
const isFormValid = formFields.every(
    field => field.required ? field.value.length > 0 : true
);
console.log(isFormValid); // true

方法組合使用

這些方法可以鏈?zhǔn)秸{(diào)用,解決復(fù)雜問題:

const data = [
    { id: 1, name: 'John', score: 85, active: true },
    { id: 2, name: 'Jane', score: 92, active: false },
    { id: 3, name: 'Bob', score: 78, active: true },
];

// 獲取活躍用戶的平均分
const averageScore = data
    .filter(user => user.active) // 篩選活躍用戶
    .map(user => user.score) // 提取分?jǐn)?shù)
    .reduce((acc, curr, _, arr) => acc + curr / arr.length, 0); // 計(jì)算平均值

console.log(averageScore); // 81.5

性能優(yōu)化方面

避免在forEach中使用async/await:

// 不推薦
array.forEach(async item => {
    await process(item);
});

// 推薦
for (const item of array) {
    await process(item);
}

大數(shù)據(jù)量處理時考慮使用for…of:

// 處理大數(shù)組時更高效
for (const item of largeArray) {
    // 處理邏輯
}

合理使用break和continue:

// 使用some代替forEach提前退出
const found = array.some(item => {
    if (condition) {
        // 找到后立即退出
        return true;
    }
    return false;
});

歡迎大家補(bǔ)充。

責(zé)任編輯:趙寧寧 來源: JavaScript
相關(guān)推薦

2024-03-21 14:27:13

JavaScript數(shù)組

2025-02-17 11:10:49

2024-01-31 12:13:02

JavaScriptSet元素

2022-11-13 15:33:30

JavaScript數(shù)組開發(fā)

2023-02-23 16:49:11

ES6技巧

2023-07-04 15:52:49

JavaScript數(shù)組

2022-11-23 16:12:57

JavaScript數(shù)據(jù)類型數(shù)組

2025-03-04 13:00:00

JavaScrip代碼語言

2025-01-10 08:38:16

2021-09-03 10:08:53

JavaScript開發(fā) 代碼

2024-09-10 08:35:57

2022-10-08 23:46:47

JavaScript對象開發(fā)

2020-03-19 15:30:08

JavaScript數(shù)組字符串

2023-11-14 16:57:10

2019-07-25 10:08:05

JavaScript數(shù)組轉(zhuǎn)換

2024-10-07 10:00:00

Python代碼編碼

2023-03-09 15:45:36

ES6編碼技巧數(shù)組

2025-01-09 12:00:00

JavaScript前端數(shù)組

2022-05-06 12:03:16

數(shù)組Javascript

2023-09-07 16:28:46

JavaScrip
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號