嗨,我正在用 JavaScript 编写一个函数
问题:定义一个不接受任何参数的函数viewCart。此函数应循环购物车中的每个商品以打印出“您的购物车中有[商品和价格对]。”。如果您的购物车中没有任何东西,该函数应该打印出“您的购物车是空的。”。
这就是我所拥有的
var cart = [];
function setCart(newCart) {
cart = newCart;
}
function getCart() {
return cart;
}
function addToCart(item) {
var price = Math.floor(Math.random() * 10);
cart.push({
item: price
});
console.log(item + " has been added to your cart.");
return cart;
}
function viewCart() {
if (cart.length != 0) {
var newArray = [];
for (var i = 0, l = cart.length; i < l; i++) {
var ItemPriceObj = cart[i];
var item = Object.keys(ItemPriceObj);
var price = ItemPriceObj['item'];
newArray.push(` ${item} at \$${price}`)
}
console.log(`In your cart, you have ${newArray}.`);
} else {
return console.log('Your shopping cart is empty.');
}
}
我的输出:
'In your cart, you have socks at $undefined, puppy at $undefined, iPhone at $undefined.'
想要的输出:
'In your cart, you have socks at $3, puppy at $23, iPhone at $400.'
最佳答案
来自 Tibrogargan 的评论:
function viewCart() {
if (cart.length != 0) {
var newArray = [];
for (var i = 0, l = cart.length; i < l; i++) {
var ItemPriceObj = cart[i];
var item = Object.keys(ItemPriceObj);
var price = ItemPriceObj['item'];
newArray.push("" + item + " at $" + price)
}
console.log("In your cart, you have " + newArray.join(","));
} else {
return console.log('Your shopping cart is empty.');
}
}
使用“插值字符串”在 Javascript 中无效,您必须将它们连接起来
关于javascript - 在 JavaScript 中,如何获取数组内对象的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40231213/