【问题标题】:Adding up values to an associative array element - Javascript将值添加到关联数组元素 - Javascript
【发布时间】:2017-12-28 21:46:26
【问题描述】:

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

代码:

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

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&lt;-&gt;big string here&lt;-&gt;123.2&lt;-&gt;2017-12-28&lt;-&gt;2017-12-28&lt;-&gt;2017-12-28&lt;-&gt;another string here&lt;-&gt;string&lt;-&gt;string&lt;-&gt;string|Company name&lt;-&gt;big string here&lt;-&gt;123.2&lt;-&gt;2017-12-28&lt;-&gt;2017-12-28&lt;-&gt;2017-12-28&lt;-&gt;another string here&lt;-&gt;string&lt;-&gt;string&lt;-&gt;string|,然后继续。

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

希望你能帮助我。

【问题讨论】:

  • sp2arr1 中有什么内容?
  • console.log(sp3[2]) 不应该是sp3[1]sp2$arr1 中的内容是什么?
  • 未知数太多。花几分钟阅读How to Askminimal reproducible example
  • 所以现在的主要部分是我们无法在没有样本输入和预期结果的情况下重现显示的内容。足以运行它来重现您的问题
  • 通过“sp2arr1 中有什么?”,我的意思是你应该在你的问题中提供一个例子,以便其他人可以复制。

标签: javascript jquery arrays operators associative-array


【解决方案1】:

你得到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])); 

【讨论】:

  • 你完全正确。它工作得很好。非常感谢您的解释。
猜你喜欢
  • 2011-10-23
  • 2012-01-23
  • 1970-01-01
  • 1970-01-01
  • 2012-01-09
  • 2017-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多