gpt4 book ai didi

javascript - 将连续调用的函数中的值保存到数组中

转载 作者:行者123 更新时间:2023-11-28 02:14:47 26 4
gpt4 key购买 nike

我有一个函数,当需要读取文件夹中的文件时会调用该函数。在这种情况下,由于我在该文件夹中有 3 个文件,因此它被连续调用 3 次。我需要将所有文件信息保存到数组 mapped_data2 中,如下所示:

mapped_data2[0] = inner_data1 //first file info, 
mapped_data2[1] = inner_data2 //second file info etc.

但是使用我的代码我只获得了第一个文件信息 3 次。我对全局变量有点困惑,如果您能指出问题,我将不胜感激。

这是代码:

var mapped_data = [];
var mapped_data2 = [];
function o(msg) {
if (msg.data) {
var inner_data = [];
var lines = msg.data.split('\n'); //read lines of a file
for (var i = 2; i < lines.length; i++) {
if (lines[i].length > 0) {
.. //do same data format here
inner_data.push([son, vactual, voutput]);
}
}
mapped_data = inner_data;
}
else {
if (msg.topic == "/somefolder/somefolder") {
for (var i = 0; i < msg.args.length; i++) {
var filename = msg.args[i];
aw.get(filename);
}
}
}
}

function de() { //where i wanted to use these files info
for (var i = 0; i < 3; i++) {
mapped_data2[i] = { key: "Group" + (i + 1), values: mapped_data };
}

var datam = mapped_data2;
var den = JSON.stringify(datam);
document.write(den);
};

function init() {
..//create new client called aw for the server application and start it;
..//if the connection is established:
aw.onmessage = o;
aw.get("/somefolder/somefolder"); // request list of files in a folder
};
//when html page is being onload, call the functions init() and de()

最佳答案

var mapped_data2 = [];                   

function o(msg) {
var mapped_data = []; // this doesn't need to be global
if (msg.data) {
var inner_data = [];
...
mapped_data = inner_data;
} else {
...
}

mapped_data2.push({ key: "Group" + mapped_data2.length + 1, values: mapped_data };)
// do more stuff as in den()
}

关于javascript - 将连续调用的函数中的值保存到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16540811/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com