簡體   English   中英

匯總數組中的值-Javascript

[英]Summing up the values in an array - Javascript

我有一個包含25個插槽的數組,每個插槽都單擊相應的按鈕填滿。 我在總結數組的值時遇到問題。 我努力了

for(var k = 0; k < price.length; k++)
{
    totalPrice += price[k] << 0;
}

但這似乎只是將價格附加到先前輸出的末尾,而不是相加。

我當前的代碼是這樣的:

$("#sumArray").click(function()
{       
    a++;
    price[0] = 8.45 * a;
    alert(price[0]);
    for(var k = 0; k < price.length; k++)
    {
        totalPrice += price[k] << 0;
    }
    alert(totalPrice);
    for(var i = 0; i < 27; i++)
    {
        $("#priceHere"+i+"").append("<b>"+totalPrice+"</b>");
    }
    //$.mobile.changePage("#mainMenu1");
});

其他所有數組索引都填充在其他click函數中。

編輯:刪除了與問題無關的所有代碼,以便於閱讀。 價格數組索引可以根據單擊某個按鈕的次數而改變。

對於現代瀏覽器(IE 9+及其他)

total = price.reduce(function (prev,curr) {
   return prev + curr;
}, 0);

參考: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

在計算之前添加以下內容:

totalPrice = 0;

如果不重置該值,它將繼續添加到先前的輸出中。

由於問題一直在編輯:

$("#priceHere"+i+"").append("<b>"+totalPrice+"</b>");

確實,它說了什么。 它將總價格附加到元素。 如果要完全覆蓋該值,可以執行以下操作:

$("#priceHere"+i+"").html("<b>"+totalPrice+"</b>");

根據您的問題,您只需要這個

price = [1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5]
totalPrice = 0
for(var k = 0; k < price.length; k++) {totalPrice += price[k];}
// gives 105

但這似乎只是將價格附加到先前輸出的末尾,而不是相加。

使其為零:

totalPrice = 0

您在哪里申報pricetotalPrice

這是一個求和一個數組值的例子:

var price = [1, 2, 3, 4, 5], // example array of prices
    totalPrice = 0, // initialize to 0 so totalPrice is a number
    k; // counter that you'll use in the loop

for (k = 0; k < price.length; k++) {
  totalPrice += price[k];
}

console.log(totalPrice); // 15

請注意,JavaScript使用+運算符進行加法和字符串連接。 聽起來好像發生了將totalPrice設置為字符串(或類型強制為一個)的情況,因此,當您要添加數字時,實際上是在連接一個字符串。

這是一個看起來像的例子。 請注意,所有代碼都是相同的,除了將字符串(而不是數字)分配給totalPrice之外:

var price = [1, 2, 3, 4, 5], // example array of prices
    totalPrice = '0', // initialized as the string '0'
    k; // counter that you'll use in the loop

for (k = 0; k < price.length; k++) {
  totalPrice += price[k];
}

console.log(totalPrice); // '012345'

暫無
暫無

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

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