JavaScript:从一个函数中的2D数组中的本地CSV数据集加载数据,然后能够在另一个函数中循环数组

发布于 2025-02-12 12:37:06 字数 943 浏览 1 评论 0原文

我的问题与JavaScript和CSV文件有关。 CVS文件来自Excel,位于服务器端。 我的最终目标是能够使用这些数据进行一些统计信息...

我尝试使用Papaparse,CSV-Parser尝试了不同的方法,并且我遇到了一些错误。

以下方式似乎存在一些问题:

我使用了asynch函数getData()将其转换为2D数组,并且正在工作:

async function getData(){
    const rep=await fetch('datan2.csv')
    const data=await rep.text();
    let fin=[]
    const table=data.split('\n').slice(1)
    table.forEach(row=>{
        const colums=row.split(',');
        tab=[colums[0], colums[1],colums[2]]
        fin.push(tab)  
        });
        return fin
    }

从以下代码中,我可以轻松地循环阵列 fin

问题。现在是当我尝试在此功能之外获取此数组时:

例如,在以下代码中,打印 t 正在工作,但我无法访问数组的特定元素:

t=getData()
    console.log(t)//working
    console.log(t[0][0])// not working here

有人可以帮忙吗?因为我的最终目标是能够将阵列循环到 getData 方法。

谢谢

My problem is related to javascript and csv file. The cvs file is from a excel and is located on the server side.
My final Goal is to to be able to do some statistics with these data...

I tried different methods using papaparse, csv-parser and I was getting some errors.

the following way seems to have some issue:

I used a asynch function getData() to convert it into a 2d array and it is working:

async function getData(){
    const rep=await fetch('datan2.csv')
    const data=await rep.text();
    let fin=[]
    const table=data.split('\n').slice(1)
    table.forEach(row=>{
        const colums=row.split(',');
        tab=[colums[0], colums[1],colums[2]]
        fin.push(tab)  
        });
        return fin
    }

From the following code, I can easily loop the array fin

The problem now is when I try to get this array outside this function:

for example in the following code, where printing t is working but I cannot access a specific element of the array:

t=getData()
    console.log(t)//working
    console.log(t[0][0])// not working here

Can someone help? because my final goal is to be able to loop the array out side the getData method.

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜味超标? 2025-02-19 12:37:06

尝试用 for..of 替换foreach。喜欢

替换

table.forEach(row=>{
   const colums=row.split(',');
   tab=[colums[0], colums[1],colums[2]]
   fin.push(tab)  
});

for(const row of table){
   const colums=row.split(',');
   tab=[colums[0], colums[1],colums[2]]
   fin.push(tab)
}

Try replacing forEach with For..of. Like so

Replace

table.forEach(row=>{
   const colums=row.split(',');
   tab=[colums[0], colums[1],colums[2]]
   fin.push(tab)  
});

With

for(const row of table){
   const colums=row.split(',');
   tab=[colums[0], colums[1],colums[2]]
   fin.push(tab)
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文