JavaScript数组为csv [英] Javascript array to csv

查看:191
本文介绍了JavaScript数组为csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经按照这个帖子<一个href=\"http://stackoverflow.com/questions/14964035/how-to-export-javascript-array-info-to-csv-on-client-side\">How导出为CSV JavaScript数组信息(在客户端)?来获取写为csv文件嵌套JS数组。

I've followed this post How to export JavaScript array info to csv (on client side)? to get a nested js array written as a csv file.

该数组如下:

var test_array = [["name1", 2, 3], ["name2", 4, 5], ["name3", 6, 7], ["name4", 8, 9], ["name5", 10, 11]];

在给出的链接code很好地工作除了CSV文件的第三行后的值的所有其余的都在同一行
例如。

The code given in the link works nicely except that after the third line of the csv file all the rest of the values are on the same line e.g.

name1,2,3结果
name2,4,5结果
name3,6,7结果
name4,8,9name5,10,11等等等等

name1,2,3
name2,4,5
name3,6,7
name4,8,9name5,10,11 etc etc

任何人都可以解释为什么这是任何光线?同样使用Chrome或FF。

Can anyone shed any light on why this is? Same using Chrome or FF.

感谢

修改

http://jsfiddle.net/iaingallagher/dJKz6/

伊恩

推荐答案

引用的答案是错的。只要修改

The cited answer is wrong. Just change

csvContent += index < infoArray.length ? dataString+ "\n" : dataString;

csvContent += dataString + "\n";

BTW,引用code是最理想的了。你应该避免反复追加到一个字符串。你应该追加为一个数组,并在最后做一个array.join(\\ n)。像这样的:

BTW, the cited code is suboptimal too. You should avoid to repeatedly append to a string. You should append to an array instead, and do an array.join("\n") at the end. Like this:

var lineArray = [];
data.forEach(function (infoArray, index) {
    var line = infoArray.join(",");
    lineArray.push(index == 0 ? "data:text/csv;charset=utf-8," + line : line);
});
var csvContent = lineArray.join("\n");

至于为何引答案是错的(搞笑它已被接受!):首页,第二个参数的的forEach 的回调函数,是该指数环 - 在数组,这是没有意义的这个比较 infoArray ,这是说的项目阵列(这恰好是一个数组太)。

As to why the cited answer is wrong (funny it has been accepted!): index, the second parameter of the forEach callback function, is the index in the looped-upon array, and it makes no sense to compare this to the size of infoArray, which is an item of said array (which happens to be an array too).

这篇关于JavaScript数组为csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆