我有一个看起来像这样的结构:
Customer {
name: 'jen',
options:
[ Order {
_price: 11,
_option: 'vegan',
_name: 'V for Vegan',
_ingredients:
[ Ingredient { name: 'mint', price: 0.5 },
Ingredient { name: 'peanuts', price: 0.5 } ] },
Order {
_price: 11,
_option: 'vegetarian',
_name: 'Veggie',
_ingredients: [] } ] }
我很难退出这部分:
_ingredients:
[ Ingredient { name: 'mint', price: 0.5 },
Ingredient { name: 'peanuts', price: 0.5 } ] },
我可以注销这个:
Options: vegan
[object Object],[object Object]
Options: vegetarian
但我希望它像
Options: vegan
mint, peanuts
我的最后一次尝试是循环_ingredients,但它返回undefined。到目前为止我的代码:
getBill() {
let totalPrice = 0;
console.log(`
Your current bill:
`)
this.options.forEach((i) => {
console.log(`
Option: ${i._option}
Extra Ingredients: ${i._ingredients.forEach((j) => {j.name})}
`)
totalPrice += i._price;
})
console.log(`
Total Price: ${totalPrice} $
`)
}
答案 0 :(得分:3)
这是一个JavaScript函数错误,因为forEach
并没有实际返回任何有用的内容。如果您阅读文档,则会看到返回值明确指定为undefined
,这是您可能获得的。你需要做些什么,比如加入它们。
Extra Ingredients: ${i._ingredients.map(_i => _i.name).join(', ')}
使用Lodash或Underscore会为您提供一个map
函数,该函数也会带一个字符串:
Extra Ingredients: ${_.map(i._ingredients, 'name').join(', ')}
实际上会返回您想要的值,它会删除name
属性,然后您可以使用join
对其进行整形处理,以将其合并到格式正确的字符串列表中。