gpt4 book ai didi

javascript循环数组中的项目

转载 作者:行者123 更新时间:2023-11-30 08:41:13 27 4
gpt4 key购买 nike

我的脑子现在一片空白..我有几个月的数组:

var month_array = new Array();

month_array[0] = "January";
month_array[1] = "February";
month_array[2] = "March";
month_array[3] = "April";
month_array[4] = "May";
month_array[5] = "June";
month_array[6] = "July";
month_array[7] = "August";
month_array[8] = "September";
month_array[9] = "October";
month_array[10] = "November";
month_array[11] = "December";

我正在尝试将标记输出为:

<ul>
<li> January & Feburary </li>
<li> March & April </li>
etc.
</ul>

遍历数组不是问题,但我现在无法弄清楚的是一种优雅的方法来遍历数组中的每 2 个项目..

我可以通过使用下面的方式按照我需要的方式格式化数组来做到这一点,但我认为这不是一个好的方向,因为它是多余的。

var months =  month_array.map(function(elem,i,arr){
return [elem, (i+1<arr.length) ? arr[i+1] : null];
}).filter(function(elem,i){
return (i%2);
});

有人知道按数组中的 2 个项目分组的最佳方法吗?

最佳答案

有时 .for loop 就足够了!你为什么不在 for 循环 month_array[++i]; 中试试这个呢? > 声明:

演示 1:

var month_array = new Array();
var cList = $('ul.mylist')
month_array[0] = "January";
month_array[1] = "February";
month_array[2] = "March";
month_array[3] = "April";
month_array[4] = "May";
month_array[5] = "June";
month_array[6] = "July";
month_array[7] = "August";
month_array[8] = "September";
month_array[9] = "October";
month_array[10] = "November";
month_array[11] = "December";

for (var i = 0, l = month_array.length; i < l; i+=2) {
var final = month_array[i] + " & " + month_array[i + 1];
var li = $('<li/>').html(final).appendTo(cList);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="mylist">
</ul>
演示 2 - 选择演示 1 更好!:
var month_array = new Array();
var cList = $('ul.mylist')
month_array[0] = "January";
month_array[1] = "February";
month_array[2] = "March";
month_array[3] = "April";
month_array[4] = "May";
month_array[5] = "June";
month_array[6] = "July";
month_array[7] = "August";
month_array[8] = "September";
month_array[9] = "October";
month_array[10] = "November";
month_array[11] = "December";

for (var i = 0, l = month_array.length; i < l; i++) {
var final = month_array[i] + " & " + month_array[++i];
var li = $('<li/>').html(final).appendTo(cList);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="mylist">
</ul>

关于javascript循环数组中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26218603/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com