簡體   English   中英

如何在javascript中添加數組的貨幣值總和

[英]How to add sum of currency values of an array in javascript

如何添加這樣的數組的貨幣值

array = [ '$0',
  '$0',
  '$14,792',
  '$152,445',
  '$1,581,033',
  '$2,988,978',
  '$4,226,419',
  '$7,254,960',
  '$10,726,945',
  '$12,657,402',
  '$35,215,787',
  '$37,968,368',
  '$7,648,445',
  '$364,237',
  '$390,395',
  '$306,080',
  '$3,641,253',
  '$4,328,363',
  '$1,360,664' ]

這是我定義的方法,我面臨的唯一問題是在第二個 array_sum 中沒有添加我從數據變量中獲取的值。

exports.GetMonthsFWSeasonFullSeasonValues = () => {
  var promises = [];
  var array_sum = 0;
  for(var month_index = 9; month_index <= 27 ; month_index++){
    const elm_xpath = utils.GetXpathForSubCategory(chosen_season_index, month_index);
    promises.push(element(by.xpath(elm_xpath)).getText());
  }
  return Promise.all(promises).then(function(data){
    if(data != null) {
      for (var array_index = 0; array_index < data.length; array_index++){
        array_sum += data[array_index];
        console.log('sum of values from months',array_sum);
      }
    } else {
      return null;
    }
  });
};

這里的問題是您正在嘗試添加兩個字符串。 + 運算符在 JS 中是重載的,所以用數字將它們相加,但用字符串將它們連接起來。 您需要使用 parseInt 或 parseFloat 將它們轉換為整數或浮點數,並去掉逗號和 $ 符號,例如:

var num = '$1,100'
parseInt(num.replace(/[$,]/g, ''))

如果你打印它,它會給 1100。 在它們采用數字格式后,您可以將它們相加。

或者,如果您可以選擇將數組中的數字存儲為數字,而無需開始使用字符串格式,請使用它。 輕松多了。

暫無
暫無

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

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