4 回答
TA贡献1864条经验 获得超6个赞
您当前的地图代码有错误。我也在示例中修复了它。
要回答您的问题,您需要使用过滤功能来查找您需要的项目。
function Customer (name, itemsPurchased, numberOfItems) {
this.name = name;
this.itemsPurchased = itemsPurchased;
};
var Customers = [
new Customer("Tim", ["milk", "Coke", "butter", "chips"]),
new Customer("Sam", ["flour", "sugar", "vanilla", "butter", "chocolate chips", "brown sugar"]),
new Customer("Sally", ["turkey", "stuffing", "gravy"]),
]
// how to extract all purchases with .map
const allPurchases = Customers.map(function(element) {
return element.itemsPurchased.length // firstly lenght has to be looking at your array
})
// how to filter to all over 5 purchases
const over5Items = Customers.filter(customer => customer.itemsPurchased.length > 5);
console.log (allPurchases)
console.log (over5Items)
TA贡献1893条经验 获得超10个赞
您不想使用地图,而是想使用过滤器。过滤器只会返回匹配的元素。
function Customer (name, itemsPurchased, numberOfItems) {
this.name = name;
this.itemsPurchased = itemsPurchased;
};
var Customers = [
new Customer("Tim", ["milk", "Coke", "butter", "chips"]),
new Customer("Sam", ["flour", "sugar", "vanilla", "butter", "chocolate chips", "brown sugar"]),
new Customer("Sally", ["turkey", "stuffing", "gravy"]),
]
const over5Items = Customers.filter(element =>element.itemsPurchased.length > 5);
console.log (over5Items)
TA贡献1824条经验 获得超6个赞
你实际上是在寻找Array.filter()
。
Array.map()
返回一个新数组,其元素数量与输入相同,其中每个元素都是给定函数的结果。
Array.filter()
返回一个新数组,其中每个输入元素都通过给定函数中的测试。
function Customer (name, itemsPurchased, numberOfItems) {
this.name = name;
this.itemsPurchased = itemsPurchased;
};
var Customers = [
new Customer("Tim", ["milk", "Coke", "butter", "chips"]),
new Customer("Sam", ["flour", "sugar", "vanilla", "butter", "chocolate chips", "brown sugar"]),
new Customer("Sally", ["turkey", "stuffing", "gravy"]),
];
let over5Items = Customers.filter(function(element) {
return element.itemsPurchased.length >= 5;
});
console.log(over5Items);
TA贡献1794条经验 获得超7个赞
let over5Items = Customers.map((element) => { return element.itemsPurchased.length > 5; })
添加回答
举报