xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

js Array.find vs Array.filter All In One

js Array.find vs Array.filter All In One

js 性能优化

find 仅返回第一个匹配的数组元素;
filter 返回一个新数组,包含所有匹配的数组元素;

find

The find() method returns the value of the first element in the provided array that satisfies the provided testing function.
If no values satisfy the testing function, undefined is returned.

find() 方法返回提供的数组中满足提供的测试函数的第一个元素的值。
如果没有值满足测试函数,则返回 undefined

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

filter

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

filter() 方法创建一个新数组,其中包含通过提供的函数实现的测试的所有元素。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

demos

const a = [1,2,3,4,5];
const result = a.filter(item => {
  console.log(item)
  return item === 3;
})
// 1
// 2
// 3
// 4
// 5

result;
// [3]

// ❌ filter 遍历后返回值是一个数组,还需要通过下标或解构方式取值
result[0];
// 3
const [value] = result;;
// 3


// ❌ filter 找到第一个匹配元素不会停止遍历,知道遍历整个数组才会返回,性能低


const a = [1,2,3,4,5];
const result = a.find(item => {
  console.log(item)
  return item === 3;
})
// 1
// 2
// 3

result;
// 3

// ✅ find 遍历后返回值是一个数组元素,直接就获取到值了
// ✅ find 找到第一个匹配元素就直接返回,不会继续遍历了,性能高

image


const dynamicActionButtonKeys = [
    {
        keys: ['721', '618', '311', '641', '642', '643', '1707', '1708'],
        // 全量(行动号召按钮)可选值
        values: ['DOWNLOAD_NOW', 'DOWNLOAD_APP', 'DOWNLOAD_GAME', 'INSTALL_NOW', 'RESERVE_NOW', 'TRY_PLAY_NOW', 'TRY_NOW',],
    },
    {
        keys: ['1465', '1480', '1064'],
        // 部分(行动号召按钮)可选值
        values: ['DOWNLOAD_APP', 'DOWNLOAD_GAME', 'RESERVE_NOW',],
    },
];
// (2) [{…}, {…}]

const key = '721';
// "721"

dynamicActionButtonKeys.find(obj => obj.keys.includes(key));
// {keys: Array(8), values: Array(7)}
// keys: (8) ["721", "618", "311", "641", "642", "643", "1707", "1708"]values: (7) ["DOWNLOAD_NOW", "DOWNLOAD_APP", "DOWNLOAD_GAME", "INSTALL_NOW", "RESERVE_NOW", "TRY_PLAY_NOW", "TRY_NOW"][[Prototype]]: Object

dynamicActionButtonKeys.filter(obj => obj.keys.includes(key));
// [{…}]
// 0: {keys: Array(8), values: Array(7)} length: 1[[Prototype]]: Array(0)

refs

(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!



©xgqfrms 2012-2021

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2021-10-09 16:12  xgqfrms  阅读(160)  评论(2编辑  收藏  举报