【问题标题】:How to loop the array of items by two and put to another array in jquery?如何将项目数组循环两个并放入jquery中的另一个数组?
【发布时间】:2019-02-14 01:53:28
【问题描述】:

这是我制作数组的方法:

var data = [];
$('tbody > tr','#iddetails').each(function(){
    var idtype   = $('.input-IDtype',this).val();
    var idnumber = $('.input-IDnumber',this).val();
    data.push(idtype, idnumber);
});

输出:

data = [1,2,3,4,5,6]

我希望我的 newdata 数组应该是这样的输出:

newdata = [

[0] 1,2

[1] 3,4

[2] 5,6

]

如何使我的 newdata 数组看起来像这样?

【问题讨论】:

    标签: jquery arrays loops


    【解决方案1】:

    实际上,对您的原始代码进行简单修改即可生成您预期的新数组:

    var data = [];
    
    $('tbody > tr','#iddetails').each(function()
    {
        var idtype   = $('.input-IDtype',this).val();
        var idnumber = $('.input-IDnumber',this).val();
    
        // Note here we push a new array with the pair [idtype, idnumber]
        // into data array.
        data.push([idtype, idnumber]);
    });
    

    【讨论】:

      【解决方案2】:

      您可以使用Array#reduceArray#slice 的组合

      const data = [1, 2, 3, 4, 5, 6];
      
      const newData = data.reduce((memo, val, i, originalData) => {
        if (i % 2 === 0) {
          memo.push(originalData.slice(i, i + 2))
        };
        return memo;
      }, [])
      
      console.log(newData);

      【讨论】:

        猜你喜欢
        • 2021-06-05
        • 1970-01-01
        • 1970-01-01
        • 2013-12-07
        • 2017-06-22
        • 1970-01-01
        • 1970-01-01
        • 2022-06-15
        • 2016-01-08
        相关资源
        最近更新 更多