你的错误:如果我们查看你的控制台截图,我们会发现在数组代码中,你将一些对象和数组弄混在了一起。在你的代码中有类似这样的内容:
var array =
[
[question1: "A", question2: "A"],
[question1: "A B", question2: "B"]
]
但这是不正确的,应该像这样:
var array =
[
{question1: "A", question2: "A"},
{question1: "A B", question2: "B"}
];
你需要纠正它。
工作样例
请参见此Codepen演示,因为StackOverflow片段在沙箱中,因此无法使用。
var array =
[
{
question1: "А",
question2: "А",
question3: "mike",
question1_A: "TRUE",
question1_B: "FALSE",
question1_C: "FALSE",
question1_D: "FALSE"
},
{
question1: "A В",
question2: "В",
question3: "dan",
question1_A: "TRUE",
question1_B: "TRUE",
question1_C: "FALSE",
question1_D: "FALSE"
},
{
question1: "B C D",
question2: "А В С",
question3: "tango",
question1_A: "FALSE",
question1_B: "TRUE",
question1_C: "TRUE",
question1_D: "TRUE"
},
{
question1: "A D",
question2: "С",
question3: "charlie",
question1_A: "TRUE",
question1_B: "FALSE",
question1_C: "FALSE",
question1_D: "TRUE"
},
{
question1: "В",
question2: "А",
question3: "bob",
question1_A: "FALSE",
question1_B: "TRUE",
question1_C: "FALSE",
question1_D: "FALSE"
},
{
question1: "C D",
question2: "А",
question3: "john",
question1_A: "FALSE",
question1_B: "FALSE",
question1_C: "FALSE",
question1_D: "FALSE"
}
];
function downloadCSV()
{
var csv = Papa.unparse(array);
var csvData = new Blob([csv], {type: 'text/csv;charset=utf-8;'});
var csvURL = null;
if (navigator.msSaveBlob)
{
csvURL = navigator.msSaveBlob(csvData, 'download.csv');
}
else
{
csvURL = window.URL.createObjectURL(csvData);
}
var tempLink = document.createElement('a');
tempLink.href = csvURL;
tempLink.setAttribute('download', 'download.csv');
tempLink.click();
}
<script src="https://www.papaparse.com/resources/js/papaparse.js"></script>
<input type="button" value="download CSV" onclick="downloadCSV()">
欲知详情,请参阅Papa的unparse
函数文档。
tempLink.remove()
将防止它们在页面上累积。 - Ben Winding