我正在尝试用javascript开发一个简单的横幅旋转。
如何确保只有值为"active":1的数组包含在shuffle中?
<div id="ad-container"></div>
<script>
var banner = [{
"img": "https://DOMAIN.TLD/IMG.JPG",
"url": "https://LINK.DOMAIN.TLD",
"maxWidth": 468,
"active": 1
},
{
"img": "https://DOMAIN.TLD/IMG2.JPG",
"url": "https://LINK2.DOMAIN.TLD",
"maxWidth": 468,
"active": 0
}
,
{
"img": "https://DOMAIN.TLD/IMG3.JPG",
"url": "https://LINK3.DOMAIN.TLD",
"maxWidth": 468,
"active": 1
}
];
function shuffle(banners) {
var j, x, i;
for (i = banners.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = banners[i];
banners[i] = banners[j];
banners[j] = x;
}
return banners;
}
shuffle(banner);
document.getElementById('ad-container').innerHTML = '<a href="' + banner[0]["url"] + '"><img src="' + banner[0]["img"] + '" style="width: 100%;height: auto;max-width: ' + banner[0]["maxWidth"] + 'px;"></a>';
</script>
值为"active"的所有数组:0不应包含在shuffle中。
也许有人知道如何改进shuffle/代码,或者如果同一页面上包含更多document.getElementById,如何防止同一横幅在页面上多次显示。
提前谢谢。
只需过滤数组。
var banner = [{
"img": "https://DOMAIN.TLD/IMG.JPG",
"url": "https://LINK.DOMAIN.TLD",
"maxWidth": 468,
"active": 1
},
{
"img": "https://DOMAIN.TLD/IMG2.JPG",
"url": "https://LINK2.DOMAIN.TLD",
"maxWidth": 468,
"active": 0
}
,
{
"img": "https://DOMAIN.TLD/IMG3.JPG",
"url": "https://LINK3.DOMAIN.TLD",
"maxWidth": 468,
"active": 1
}
];
let activeParts = banner.filter( info => info.active );
console.log( activeParts );
// do whatever, e.g.:
// shuffle( activeParts );