繁体   English   中英

将值添加到关联数组元素 - Javascript

[英]Adding up values to an associative array element - Javascript

我在向数组中的现有值添加值时遇到了一些问题。

编码:

这一切都来自设置为父页面中隐藏元素值的大字符串。

var parent = $(window.opener.document).contents();
var data = parent.find("#hdn").val();

var sp1 = data.split("=x=");
$('#timerange').text(sp1[0]); // this is where I put the first part of the string

var sp2 = sp1[1].split("|"); // the remains of it will be used to fill arr1
var arr1 = {};

  $.each(sp2, function(i, value){
    if(value != ''){
      var sp3 = value.split("<->");

      arr1[sp3[0]] += parseFloat(sp3[2]); // this is where the problem goes. i can't sum the new value with the existing value of this element, it outputs "NaN" no matter what

      $('#tableprnt tbody').append('<tr><td>'+sp3[0]+'</td><td>'+sp3[1]+'</td><td>'+sp3[2]+'</td><td>'+sp3[3]+'</td><td>'+sp3[4]+'</td><td>'+sp3[5]+'</td><td>'+sp3[6]+'</td><td>'+sp3[7]+'</td><td>'+sp3[8]+'</td><td>'+sp3[9]+'</td></tr>');
    }
  })

  console.log(arr1);

这样做的目的是将此信息附加到表格中,以便我可以打印它。

data具有来自父页面的字符串,如下所示: 2017-12-28 - 2017-12-28=x=Company name<->big string here<->123.2<->2017-12-28<->2017-12-28<->2017-12-28<->another string here<->string<->string<->string|Company name<->big string here<->123.2<->2017-12-28<->2017-12-28<->2017-12-28<->another string here<->string<->string<->string| 它继续。

arr1 (sp3[0] [string])每个元素都应该有其各自值的总和(sp3[2] [float]) ,但即使我使用的是parseFloat() ,我能得到的每一个元素都是NaN parseFloat() . Console显示*"{element 1: NaN, element 2: NaN}"* 我错过了什么?

希望您能够帮助我。

您得到NaN是因为当您尝试增加键company_name的值时应该返回该值

arr1[sp3[0]] += parseFloat(sp3[2]);

这将失败或说将在值的第一次迭代中存储NaN ,因为针对键/属性“公司名称”的实际值将是undefined并且在undefined上调用parseFloat()将返回您需要检查对象的NaN已经定义了属性,然后将值增加/添加到现有值,如果是第一次,则分配该值。 将上面的行更改为以下内容

arr1[sp3[0]] = (arr1.hasOwnProperty(sp3[0])) ? (arr1[sp3[0]] + parseFloat(sp3[2])) : (parseFloat(sp3[2])); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM