javascript - 使用给定数字对 JSON 数组进行分组

标签 javascript arrays json ajax

我有一组通过 WordPress Ajax 填充的 JSON 数据。

["http://inovar.dev/wp-content/uploads/2016/11/FR991-Eco-Oak-A1.jpg",…]

现在总共有69个项目。我怎么能把它分成每组18个项目。然后像这样包起来:

<div class="slide">
<a class="floor-thumbnail"><img src="/wp-content/uploads/2017/01/BG_2-3.jpg" alt=""/></a>
<a class="floor-thumbnail"><img src="/wp-content/uploads/2017/01/BG_2-3.jpg" alt=""/></a>
<a class="floor-thumbnail"><img src="/wp-content/uploads/2017/01/BG_2-3.jpg" alt=""/></a>
<a class="floor-thumbnail"><img src="/wp-content/uploads/2017/01/BG_2-3.jpg" alt=""/></a>
<a class="floor-thumbnail"><img src="/wp-content/uploads/2017/01/BG_2-3.jpg" alt=""/></a>
<a class="floor-thumbnail"><img src="/wp-content/uploads/2017/01/BG_2-3.jpg" alt=""/></a>

最佳答案

这样就可以了:

var arr = ["http://inovar.dev/wp-content/uploads/2016/11/FR991-Eco-Oak-A1.jpg",…];

var itemsPerBlock = 18;

var htmlStr = '<div class="slide">'
arr.forEach( function (d, idx) {
    htmlStr += '<a class="floor-thumbnail"><img src="' +
               d.split('inovar.dev')[1] + 
               '" alt=""/></a>';

    if ((idx+1) % itemsPerBlock == 0 ) 
        htmlStr += '</div><div class="slide">';
})

htmlStr += '</div>';

$('body').append(htmlStr); //append this to body

关于javascript - 使用给定数字对 JSON 数组进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42790601/

相关文章:

javascript - 使用 $http.get 从 AngularJS 中的 URL 读取 JSON

javascript - 在页面加载结束时运行 Javascript

javascript - 我想滚动放大和缩小图像,但该图像上的图钉也保持正确定位。查询

javascript - 按多个条件过滤数组

javascript - 如何在javascript中检查对象的属性数组是否为空

java - 没有附加适配器,在 fragment 中使用 reyclerview 和 json 跳过布局

javascript - 在javascript函数中使用局部变量获取表单元素

javascript - 从顶部和底部偏移固定 div

使用动态数组的 C++ 逻辑错误

Json 字段可以是 string 或 bool 到 struct 中