gpt4 book ai didi

javascript - JS 数组 : filter() with map() vs forEach()

转载 作者:行者123 更新时间:2023-11-30 11:03:56 25 4
gpt4 key购买 nike

<分区>

.filter() + .map().forEach() 哪个更优化?

这是一个对象数组示例:

var personnel = [
{
id: 5,
name: "Luke Skywalker",
pilotingScore: 98,
shootingScore: 56,
isForceUser: true,
},
{
id: 82,
name: "Sabine Wren",
pilotingScore: 73,
shootingScore: 99,
isForceUser: false,
},
{
id: 22,
name: "Zeb Orellios",
pilotingScore: 20,
shootingScore: 59,
isForceUser: false,
},
{
id: 15,
name: "Ezra Bridger",
pilotingScore: 43,
shootingScore: 67,
isForceUser: true,
},
{
id: 11,
name: "Caleb Dume",
pilotingScore: 71,
shootingScore: 85,
isForceUser: true,
},
];

假设我们想要获得仅提供名称和 ID 的最终数组,其中 isForceUser=true

[ { id: 5, name: 'Luke Skywalker' }, 
{ id: 15, name: 'Ezra Bridger' }, 
{ id: 11, name: 'Caleb Dume' } ] 

现在有两种方法可以解决:

  1. 通过.filter()+.map(),如下图:
var APersonnel = personnel
.filter((person) => person.isForceUser)
.map((person) => ({ id: person.id, name: person.name }));
  1. 通过使用 .forEach() 并推送一个新对象:
var BPersonnel = [];
personnel.forEach((person) => {
if (person.isForceUser) {
BPersonnel.push({ id: person.id, name: person.name });
}
});

上面定义的解决方案中哪一个更好,为什么?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com