【问题标题】:How to create and print list of sub arrays out of one long array如何从一个长数组中创建和打印子数组列表
【发布时间】:2013-04-21 07:51:47
【问题描述】:

我有一个长度不等的长字符串数组,因为我正在从数据库表中提取字符串,这些字符串将由用户提交动态填充,但是,该长数组将由一组重复的 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

【问题讨论】:

    标签: javascript jquery for-loop multidimensional-array


    【解决方案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(' '));
    }
    

    【讨论】:

      猜你喜欢
      • 2011-10-24
      • 1970-01-01
      • 1970-01-01
      • 2011-05-25
      • 2014-05-02
      • 1970-01-01
      相关资源
      最近更新 更多