将值添加到关联数组元素 - 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);

重点是将此信息附加到 table 以便我打印它。

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()Console 显示 *"{element 1: NaN, element 2: NaN}"*。 我错过了什么?

希望你能帮助我。

您得到的是 NaN,因为这是您尝试增加键值 company_name

时应该 return 编辑的内容
arr1[sp3[0]] += parseFloat(sp3[2]);

这会失败或者说将在值的第一次迭代中存储 NaN 因为针对 key/property "Company Name" 的实际值将是 undefined 并调用parseFloat() on undefined 将 return 你 NaN 你需要检查对象是否已经定义了 属性 然后 increment/add 值到现有值如果是第一次,则分配值。将上面的行更改为以下

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