我有这个代码:const arraySalesperson = ["John", "Alice", "Bob", "John", "John", "Alice"];const arraySales = [100, 420, 138, 89, 74, 86];const arrayGoals = [1, 2, 3, 4, 5, 6];// create a mapconst resultsBySalesperson = new Map();// traverse the list of salespersonsfor (let i = 0; i < arraySalesperson.length; i++) { const name = arraySalesperson[i]; // see if it already exists in the map let salesperson = resultsBySalesperson.get(name); if (!salesperson) { // if not, let's create an object now salesperson = { name: name, sales: 0, goals: 0 }; // store it in the map resultsBySalesperson.set(name, salesperson); } // update the object salesperson.sales += arraySales[i]; salesperson.goals += arrayGoals[i];}// here you have the map ready with both sales and goal properly accumulatedconsole.info([...resultsBySalesperson.entries()]);我需要使用属性 salesperson.sales 和 salesperson.goals。我该如何选择这些属性?我试过使用:resultsBySalesperson.get(name)resultsBySalesperson.get(salesperson.sales)resultsBySalesperson.get(salesperson.goals)但我觉得我做错了什么
3 回答
幕布斯7119047
TA贡献1794条经验 获得超8个赞
您确实需要Map.get按姓名检索销售人员,但随后它会返回一个纯 JavaScript 对象,您可以使用点表示法访问其属性。
例如:
const resultsBySalesperson = new Map([
[
"John",
{
"name": "John",
"sales": 263,
"goals": 10
}
],
[
"Alice",
{
"name": "Alice",
"sales": 506,
"goals": 8
}
]
]);
const john = resultsBySalesperson.get("John");
console.log(john.sales);
console.log(john.goals);
或者,您也可以使用括号表示法(例如,john["sales"]
)。
宝慕林4294392
TA贡献2021条经验 获得超8个赞
您可以使用解构赋值来获取所需的属性:
const {sales, goals} = resultsBySalesperson.get(name);
慕无忌1623718
TA贡献1744条经验 获得超4个赞
只需获取对象,然后获取想要的属性
person = resultsBySalesperson.get(name);
sales = person.sales;
goals = person.goals;
添加回答
举报
0/150
提交
取消