你好我们如何在jquery函数中循环一个数组。在downloadCSV函数中如果你观察项目中的意思我正在采取第0个数组。所以我现在很难编码那个数组。所以现在有n个数组。那么如何在函数内部循环呢?
<!doctype html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
</head>
<body>
<a href='#' onclick='downloadCSV({ filename: "youtubeData.csv" });'>Download CSV</a>
<script type="text/javascript">
$(document).ready(function() {});
function convertArrayOfObjectsToCSV(args) {
var result, ctr, keys, columnDelimiter, lineDelimiter, data;
data = args.data || null;
if (data == null || !data.length) {
return null;
}
columnDelimiter = args.columnDelimiter || ',';
lineDelimiter = args.lineDelimiter || '\n';
keys = Object.keys(data[0]);
result = '';
result += keys.join(columnDelimiter);
result += lineDelimiter;
data.forEach(function(item) {
ctr = 0;
keys.forEach(function(key) {
if (ctr > 0) result += columnDelimiter;
result += item[key];
ctr++;
console.log("columnDelimiter " + result);
});
result += lineDelimiter;
});
return result;
}
function downloadCSV(args) {
var youtubeData = [];
var data, filename, link;
$.getJSON('https://www.googleapis.com/youtube/v3/commentThreads?key=""&textFormat=plainText&part=snippet,replies&videoId=eDHFc24mp38&maxResults=60', function(data) {
youtubeData.push({
"comments": data.item[0].snippet.topLevelComment.snippet.authorDisplayName,
});
console.log(data.item[0].snippet.topLevelComment.snippet.authorDisplayName);
var csv = convertArrayOfObjectsToCSV({
data: youtubeData
});
if (csv == null) return;
filename = args.filename || 'export.csv';
if (!csv.match(/^data:text\/csv/i)) {
csv = 'data:text/csv;charset=utf-8,' + csv;
}
data = encodeURI(csv);
link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', filename);
link.click();
});
}
</script>
</body>
</html>
答案 0 :(得分:0)
您可以使用for循环迭代data.item,如下所述:
for(var i = 0; i < data.item.length; i++) {
youtubeData.push({
"comments": data.item[i].snippet.topLevelComment.snippet.authorDisplayName,
});
}