将对象压入数组,然后通过结果数据结构进行循环

Pushing Object into Array then Looping Through Resulting Data Structure

本文关键字:结果 数据结构 循环 然后 对象 数组      更新时间:2023-09-26
var cartTotal = [];
var priceValue = x;
var priceID = y;
在定义了上面的空数组之后,我有一个循环,其中包括以下内容:
cartObj = {};
cartObj.priceID = priceValue;
cartTotal.push(cartObj);
total(priceID);

对上面的代码循环几次之后,得到的cartTotal数组是否看起来像这样:

cartTotal = [{priceID:priceValue},{priceID:priceValue}]       ?

我问的原因是因为我试图将priceID传递给下面的total函数,以便对所有priceValue数字求和。为什么在总函数中,是a。价格定义?cartTotal。length alert表示我有一个具有多个值的数组,因此该数组在函数中被识别。

function total(price){
alert(cartTotal.length);
totalPrice = 0;
for(var i=0;i<cartTotal.length; i++){
a = cartTotal[i];
itemPrice = parseInt(a.price);
totalPrice += itemPrice;
} 
}

您需要a.priceID。那是你用key存储的。

不需要a,只使用数组本身。另外,因为它是一个价格,所以最好使用float。

代码:

function total(price){
    alert(cartTotal.length);
    totalPrice = 0;
    var itemPrice;
    for(var i=0; i<cartTotal.length; i++){
        itemPrice = parseFloat(carTotal[i].priceID).toFixed(2);
        totalPrice += itemPrice;
    } 
}

问题:为什么要将price作为参数传递给函数?