附加到二维数组的Javascript [英] Javascript Appending to 2-D Array
问题描述
我正在尝试将数组追加到数组。我期望输出为:
I am trying to append an array to an array. I am expecting the output to be something like:
[[Dep,POR],[14073,99.25],[14072,0.06]]
但是我得到:
Dep,POR,14073,99.25,14072,0.06
这是我到目前为止的内容:
Here's what I have so far:
function get_historical() {
var well = document.getElementById('wellSelect');
var selected_well = well.options[well.selectedIndex].value;
var hist_json_obj = JSON.parse(Get("/get_historical/" + selected_well));
hist_por = ['Dep','POR'];
for (var item in hist_json_obj) {
if (hist_json_obj.hasOwnProperty(item)) {
var dep = hist_json_obj[item].dep;
var por = hist_json_obj[item].por;
var arr_por = [dep, parseFloat(por)];
hist_por.push(arr_por);
}
}
document.write(hist_por);
}
推荐答案
初始化 hist_por
,您希望它是一个二维数组,而您目前只有一个数组。因此,您希望将其实例化为:
When you initialize hist_por
, you want that to be a 2-D array whereas you currently have just a single array. So you would want to change its instantiation to:
hist_por = [['Dep','POR']]; // [[ ... ]] instead of [ ... ]
也按@justrusty的回答,将其传递给 document.write()
时,需要 JSON.stringify(hist_por)
。这是更重要的部分,因此他的回答应该被接受。
Also per @justrusty's answer, you need to JSON.stringify(hist_por)
when you pass it to document.write()
. This is the more important piece so his answer should be accepted.
因此整个代码块将变为:
So the whole code block would become:
function get_historical() {
var well = document.getElementById('wellSelect');
var selected_well = well.options[well.selectedIndex].value;
var hist_json_obj = JSON.parse(Get("/get_historical/" + selected_well));
hist_por = [['Dep','POR']];
for (var item in hist_json_obj) {
if (hist_json_obj.hasOwnProperty(item)) {
var dep = hist_json_obj[item].dep;
var por = hist_json_obj[item].por;
var arr_rop = [dep, parseFloat(por)];
hist_por.push(arr_por);
}
}
document.write(JSON.stringify(hist_por));
}
这篇关于附加到二维数组的Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!