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; })
添加回答
舉報