简体   繁体   English

用JavaScript循环处理两个数组

[英]Two arrays in a loop with JavaScript

I have a problem in my script. 我的脚本有问题。 I have two arrays, which is the data and also a month. 我有两个数组,分别是数据和一个月。

What I want is that to append two merge the month in data, but then only 1 value shows in month, here is my code: 我想要的是在数据中追加两个合并月份,但是然后在月份中仅显示1个值,这是我的代码:

const months = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];

ali_fcr.get().then((d) => {
  let store = '';

  let getTotal = d.reduce(function(x, y) {
    return (x * 1) + (1 * y);
  });

  let new_array = d.map((data) => {
    for (let i = 0; i < data.length; i++) {
      return '<td class="ta"><center><a class="ta" href="' + months[i] + '/ali">' + data + '</a></center></td>';
    }
  });

  new_array.unshift('<td>Case Receive</td>');
  new_array.push('<td style="color:red; text-align:center;">' + getTotal + '</td>');
  new_array.forEach((data) => {
    store += data;
  });

  _doc.querySelector('tr[data-alicase-category="cr"]').innerHTML = store;

});

but the result in my html is only january value of month. 但结果在我的HTML仅january月的值。

Jaromanda X said it in the comments, but it's your for loop inside a function making use of the return keyword. Jaromanda X在评论中说过,但这是您使用return关键字的函数中的for循环。 Non-function blocks (ex: if, while, for) do not return anything, so calling return will “bubble up” to the function scope, in this case causing your map function to return after only one iteration. 非功能块(例如:if,while,for)不返回任何内容,因此调用return将“冒泡”到函数范围,在这种情况下,导致map函数仅在一次迭代后返回。

Solution: consider pushing that html string into an array, then returning htmlarray.join('') out of the map function. 解决方案:考虑将html字符串推入数组,然后从map函数中返回htmlarray.join('') Now your loop can complete and the data will be returned together. 现在您的循环可以完成,数据将一起返回。

I think this return is avoiding make a loop of data , it's just taking the first one: 我认为这种回报避免了造成data循环,只是采用了第一个:

let new_array = d.map((data) => {
        for(let i = 0; i < data.length; i++) {
            return '<td class="ta"><center><a class="ta" href="' + months[i] + '/ali">' + data + '</a></center></td>';   
        }
    });

I suggest you to keep with array functions like: 我建议您继续使用数组函数,例如:

let new_array = d.map(data => data.map(
  (d_data, i) => '<td class="ta"><center><a class="ta" href="' + months[i] + '/ali">' + data + '</a></center></td>'));

Also, I don't know how data is structured, so I have no idea if you want to push inside <td> the value of d_data instead of data . 另外,我也不知道data的结构,所以我不知道是否要在d_data而不是data推入<td>值。

Anyway, I hope it helps. 无论如何,我希望它会有所帮助。 Happy coding! 编码愉快! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM