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

问题描述 投票:-1回答:1

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

代码:

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

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])的总和,但即使我使用NaN,我所能获得的每一个都是parseFloat()Console显示*"{element 1: NaN, element 2: NaN}"*。我错过了什么?

希望您能够帮助我。

javascript jquery arrays operators associative-array
1个回答
0
投票

你正在获得NaN,因为当你试图增加密钥company_name的值时应该返回

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

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

arr1[sp3[0]] = (arr1.hasOwnProperty(sp3[0])) ? (arr1[sp3[0]] + parseFloat(sp3[2])) : (parseFloat(sp3[2])); 
© www.soinside.com 2019 - 2025. All rights reserved.