![](/img/trans.png)
[英]How can I loop through array and sum only half the items? (javascript)
[英]How can I half the array
我正在學習編碼,我正在嘗試這個 javascript object 方法課程。 我目前堅持這種方法。 我想讓具有三個不同數字(10,20,5)的數組為/2。 我不明白為什么它會返回 NaN。 感謝您的閱讀。
shirtPrice = 10
jeanPrice = 20
shoePrice = 5
shoppingList = [shirtPrice,jeanPrice,shoePrice];
const shoppingDiscountDay = {
discountedItems: {
calculateItemsDiscount() {
return shoppingList/2; //return NaN
},
}
}
console.log(shoppingDiscountDay.discountedItems.calculateItemsDiscount());
嘗試使用.map()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
const shoppingDiscountDay = {
discountedItems: {
calculateItemsDiscount() {
const itemsHalfPrice = shoppingList.map(item=>item/2)
return itemsHalfPrice;
},
}
}
您不能划分數組,您需要划分其中的每個元素。
您可以使用.map
方法,該方法在數組的每個元素上應用 function 並返回帶有結果的新數組
shirtPrice = 10 jeanPrice = 20 shoePrice = 5 shoppingList = [shirtPrice, jeanPrice, shoePrice]; const shoppingDiscountDay = { discountedItems: { calculateItemsDiscount() { return shoppingList.map(itemPrice => itemPrice / 2); }, } } console.log(shoppingDiscountDay.discountedItems.calculateItemsDiscount());
您不能對數組執行“/”操作。 它旨在對數字執行。 而是試試這個。
shirtPrice = 10
jeanPrice = 20
shoePrice = 5
shoppingList = [shirtPrice,jeanPrice,shoePrice];
const shoppingDiscountDay = {
discountedItems: {
calculateItemsDiscount() {
for(let i = 0; i < shoppingList.length; i++){
shoppingList[i] = shoppingList[i]/2;
}
return shoppingList;
},
}
}
console.log(shoppingDiscountDay.discountedItems.calculateItemsDiscount());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.