我有一长串的字符串会有不同的长度,因为我从数据库表中提取字符串,这些数据库表将由用户提交动态填充,但是,长数组将由重复的6组成。变量。所以我想在每个第6个索引处切片,将我切成的数组转换成数组,然后将这些子数组的列表打印到页面。 这就是我到目前为止所做的:
//I'm using Parse as my database and the find() method is one way you query it.
var search = [];
query.find({
success: function(results) {
//loop through results to get the key-value pair of each row
for (i = 0; i < results.length; i++){
activity = results[i].get("activity");
scene = results[i].get("location");
neighborhood = results[i].get("neighborhood");
date = results[i].get("date");
details = results[i].get("details");
time = results[i].get("time");
//Here I'm pushing the row of the six variables into an array, but since there will be multiple rows on the table from multiple submissions, the array will contain however many rows there are.
search.push(activity, scene, neighborhood, date, details, time);
//my second array
var search2 = [];
//This is that part I'm unsure of. I want to loop through the search array slicing it at every 6th index creating multiple sub arrays. I then want to write the list of those sub arrays to the page
for(i=0; i < search.length; i+=6){
search2 = search.slice(0,6);
}
//this is the div I want to write the arrays to.
$("#mainDiv").text(search2);
};// closes success function
答案 0 :(得分:1)
为什么不将每个记录的数据集作为数组添加到搜索数组中,而不是将每个单独的字段推送到搜索数组上,然后将每个字段组合在一起?
search.push([activity, scene, neighborhood, date, details, time]);
这样,当您遍历搜索数组以打印出每个记录的值时,您不必进行任何切片或递增6.对于每个循环,您已经拥有了所需的数组切片:
for (i = 0; i < search.length; i++) {
$('#mainDiv').append(search[i]);
}
也许我误解了您的问题,但看起来您想要将所有记录添加到#mainDiv中。如果对循环的每次迭代使用jQuery text()方法,则只需覆盖每次迭代的文本,使结果成为循环的最终值,而不是所有项的所有值。要将每条记录添加到#mainDiv,您需要使用append()方法。
您可能还想在值之间添加一些空格,假设您使用我的方法来存储数组而不是单个字段数组项:
for (i = 0; i < search.length; i++) {
$('#mainDiv').append(search[i].join(' '));
}