【问题标题】:Saving spliced arrays as separate variables using Javascript使用 Javascript 将拼接数组保存为单独的变量
【发布时间】:2020-04-20 16:50:50
【问题描述】:

我目前有一个函数,它接收一个 JSON 文档并返回所有 3000 个项目 ID。我正在使用 fetch 循环中的 ID 从 API 请求中返回有关每个项目 ID 的信息。一切都很好,但是因为每小时有 200 个请求限制,所以我想将数组拼接成 200 个单独的数组,这样我就可以每小时对每个 ID 数组进行单独调用。这个想法是在不同的时间对每个请求进行排队以保持与限制一致,然后在返回数据后,我将信息推送到相应的数组或 JSON 对象,稍后我将在我的应用程序中使用。

目前我可以将数组拼接成我想要的 ID,但我不知道如何使用循环为每个数组提供一个我可以访问的特定变量/名称。目前我得到一个带有数字的数组列表,但我想给每个数组 let array1 = [1,...200]let array2 = [201,...200] 等等。

这是我目前所拥有的:

const ItemIDs = [];
function fetchItemIDs() {
  fetch("./db.json")
    .then(function(resp) {
      return resp.json();
    })
    .then(function(item) {
      for (i in item) {
        ItemIDs.push(item[i].id);
      }
      console.log(ItemIDs);
      var e = ItemIDs;
      while (e.length) {
        console.log(e.splice(0, 200));
      }
    });
}
fetchItemIDs();

我不会提供 JSOn 文件,但简而言之,我的输出是一个包含 3000 个项目的简单数组,然后是另一个显示单独拼接数组的输出。

提前感谢您的帮助/建议。

【问题讨论】:

    标签: javascript arrays loops fetch


    【解决方案1】:

    理想情况下,您的“db”调用应该返回 X 大小的结果,您可以重复,但如果您必须使用文件中的 json,您可以实现某种基本分页,例如:

    var array = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
    
    var batch_size = 3;
    var offset = 0;
    var current_batch = [];
    var loop_count = 0;
    
    var my_cool_batches = [];
    var my_cool_batches_with_names = {};
    do{
        var current_batch = array.splice(offset, batch_size);
        if(current_batch.length>0){
            console.log(current_batch); // [ "a", "b", "c" ] then [ "d", "e", "f" ] etc
            // do something
            my_cool_batches.push(current_batch);
            my_cool_batches_with_names[ 'array_' + String(loop_count) ] = current_batch;
        }
    }while(current_batch.length>0)
    
    console.log('all done');
    

    【讨论】:

    • 我想我明白了,但我不明白如何将每个新拼接的数组保存到循环中新的动态创建的变量中。基本上,我试图将一个数组拼接 200 秒,然后将每个 200 个数字的数组保存到一个唯一的数组中,我可以稍后调用,如“array1”和“array2”,我希望创建这些变量,直到拼接完成.
    • 轻松搞定。只需将它们分配给对象或数组以供以后访问。例如见编辑。然后您可以像my_cool_batches_with_names['array_2'] 一样访问并获得第三个“批次”数组
    【解决方案2】:

    为什么不改用slice

    e1 = e.slice(0, 200)
    e2 = e.slice(201)
    

    【讨论】:

      【解决方案3】:

      既然您问过如何挑选出项目的子数组并访问它们,

      您可以将ItemIDs 设为数组数组。 现在,当您遍历

      中的项目时
      for (let i = 0; i <= item.length; i+= GROUP_SIZE ) {
           ItemIDs.push(item.slice(i, i + GROUP_SIZE));
      }
      

      您可以通过将索引分配给某个变量来跟踪当前组

      let currentGroup = 0; // track the current group
        const interval = setInterval(() => {
          if (currentGroup < ItemIds.length) {
            // you can then simply get the subgroup from index and iterate over it
            ItemIds[currentGroup].forEach(fetchSomething);  
          } else {
            clearInterval(interval);
          }
        }, INTERVAL);
      

      但是为什么,组元素,你可以简单地做

      const GROUP_SIZE = 200;
      function fetchItemIDs() {
      fetch("./db.json")
        .then(function(resp) {
          return resp.json();
        })
        .then(function(item) {
      
           // start fetching
           let currentGroup = 0;
           const interval = setInterval(() => {
             if (currentGroup >= item.length) {
               clearInterval(interval);
             } else {
               for (let i = currentGroup; i < GROUP_SIZE; i++) {
                 fetchSomething(i);
               }
             }
      
            }, INTERVAL);
          });
      }
      

      const ItemIDs = [];
      const GROUP_SIZE = 200;
      function fetchItemIDs() {
        fetch("./db.json")
          .then(function(resp) {
            return resp.json();
          })
          .then(function(item) {
           
            for (let i = 0; i <= item.length; i+= GROUP_SIZE ) {
               ItemIDs.push(item.slice(i, i + GROUP_SIZE));
             }
      
             // start fetching
             let currentGroup = 0;
            const interval = setInterval(() => {
              if (currentGroup < ItemIds.length) {
                ItemIds[currentGroup].forEach(fetchSomething);
              } else {
                clearInterval(interval);
              }
            }, INTERVAL);
          });
      }
      fetchItemIDs();

      【讨论】:

        【解决方案4】:

        您需要编写一个函数,该函数循环一个空数组,并使用一个新数组填充每个索引,该数组包含您尝试划分的数组块。

        然后你可以通过选择索引从新创建的数组中选择每个块。

        const arrayChunks = (array, size) => Array(Math.ceil(array.length / size)).fill()
          .map((entry, index) => index * size)
          .map(begin => array.slice(begin, begin + size));
        
        const values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
        const chunks = arrayChunks(values, 4);
        
        const chunk = chunks[1];
        
        console.log('Created chunks:', chunks);
        console.log('A single chunk:', chunk);

        【讨论】:

          猜你喜欢
          • 2011-03-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-05-18
          • 2012-12-31
          • 2014-04-23
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多