簡體   English   中英

在JavaScript中,我如何獲得數組內對象的值

[英]In JavaScript how do I reach the value of objects inside of an array

您好我正在用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.');
    }
}

我的輸出:

“在你的購物車里,你的襪子是$ undefined,小狗是$ undefined,iPhone是$ undefined。”

想要輸出:

“在你的購物車中,你的襪子價格為3美元,小狗價格為23美元,iPhone價格為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中無效,而是必須連接它們

您使用字符串“item”索引購物車項目,而不是實際的商品名稱。 很容易解決:

改變這一行:

var price = ItemPriceObj['item'];

對此:

var price = ItemPriceObj[item];

也許想要考慮更改購物車元素屬性名稱(主要是為了提高可讀性),還要考慮讓事情變得更容易一些,例如:

function addToCart(newItem) {
    var price = Math.floor(Math.random() * 10);
    cart.push({
        item: newItem, price: price
    });
    console.log(newItem+ " 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++) {
            newArray.push(` ${cart[i].item} at \$${cart[i].price}`)
        }
        console.log(`In your cart, you have ${newArray}.`);
    } else {
        return console.log('Your shopping cart is empty.');
    }
}

viewCart的替代方案(有些人可能會以犧牲可讀性為代價) - 但如果屬性名稱可變,這將更加冗長

function viewCart() {
    if (cart.length != 0) {
        console.log(cart.reduce( (p,e,i) => `${p}${i?',':''} ${e.item} at \$${e.price}`, "In your cart, you have" ));
    } else {
        return console.log('Your shopping cart is empty.');
    }
}

使用語言功能使代碼更“簡單”:

 var cart = []; function Item(item, price) { this.item = item; this.price = price; } Item.prototype.toString = function() { return `${this.item} at \\$${this.price}` } function addToCart(item, price) { if (!(item instanceof Item)) { if (typeof price === "undefined") { price = Math.floor(Math.random() * 10); } item = new Item(item, price); } cart.push( item ); console.log(item + " has been added to your cart."); return cart; } function viewCart() { if (cart.length != 0) { console.log(`In your cart, you have ${cart.join(", ")}`); } else { return console.log('Your shopping cart is empty.'); } } addToCart("socks", 3.00); addToCart("puppy", 23.00); addToCart("iPhone", 400.0); document.addEventListener( "DOMContentLoaded", viewCart, false ); 

這是你可以做的事情。 更新了項目名稱和價格檢索。

 var cart = []; function setCart(newCart) { cart = newCart; } function getCart() { return cart; } function addToCart(item) { var price = Math.floor(Math.random() * 10); var obj = {}; obj[item] = price; cart.push(obj); 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 itemKeys = Object.keys(itemPriceObj); var item = itemKeys.filter(function(key) { return itemPriceObj.hasOwnProperty(key) }); 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.'); } } addToCart("Sock"); addToCart("Phone"); addToCart("Tab"); addToCart("Book"); addToCart("Keyboard"); viewCart(); 

您沒有正確使用對象文字表示法。 你可能想要這樣的東西。

addToCart()更改為:

function addToCart(item) {
    var price = Math.floor(Math.random() * 10);
    cart.push({
        item: item,
        price: price
    });
    console.log(item + " has been added to your cart.");
    return cart;
}

並將viewCart()更改為:

function viewCart() {
    if (cart.length != 0) {
        var newArray = [];
        for (var i = 0, l = cart.length; i < l; i++) {
            newArray.push(` ${cart[i].item} at \$${cart[i].price}`)
        }
        var itemPriceList = newArray.join(', '); // This will concatenate all the strings in newArray and add commas in between them
        console.log(`In your cart, you have ${itemPriceList}.`);
    } else {
        return console.log('Your shopping cart is empty.');
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM