【发布时间】: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<->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。
Console 显示 *"{element 1: NaN, element 2: NaN}"*。
我错过了什么?
希望你能帮助我。
【问题讨论】:
-
sp2和arr1中有什么内容? -
console.log(sp3[2]) 不应该是
sp3[1]和sp2和$arr1中的内容是什么? -
未知数太多。花几分钟阅读How to Ask和minimal reproducible example
-
所以现在的主要部分是我们无法在没有样本输入和预期结果的情况下重现显示的内容。足以运行它来重现您的问题
-
通过“
sp2和arr1中有什么?”,我的意思是你应该在你的问题中提供一个例子,以便其他人可以复制。
标签: javascript jquery arrays operators associative-array