4 回答

TA貢獻(xiàn)1864條經(jīng)驗(yàn) 獲得超6個(gè)贊
您當(dāng)前的地圖代碼有錯(cuò)誤。我也在示例中修復(fù)了它。
要回答您的問(wèn)題,您需要使用過(guò)濾功能來(lái)查找您需要的項(xiàng)目。
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貢獻(xiàn)1893條經(jīng)驗(yàn) 獲得超10個(gè)贊
您不想使用地圖,而是想使用過(guò)濾器。過(guò)濾器只會(huì)返回匹配的元素。
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貢獻(xiàn)1824條經(jīng)驗(yàn) 獲得超6個(gè)贊
你實(shí)際上是在尋找Array.filter()
。
Array.map()
返回一個(gè)新數(shù)組,其元素?cái)?shù)量與輸入相同,其中每個(gè)元素都是給定函數(shù)的結(jié)果。
Array.filter()
返回一個(gè)新數(shù)組,其中每個(gè)輸入元素都通過(guò)給定函數(shù)中的測(cè)試。
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貢獻(xiàn)1794條經(jīng)驗(yàn) 獲得超8個(gè)贊
let over5Items = Customers.map((element) => { return element.itemsPurchased.length > 5; })
添加回答
舉報(bào)