我正在尝试使用javascript开发简单的横幅广告轮换。
我如何确保随机播放中仅包含值“ active”:1的数组?
<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的数组都不应包含在随机播放中。
也许有人知道如何改善随机播放/代码,或者如果同一页面上包含更多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 );
banner.map( value => {
if( value.active === 1 ){
return value
}
这将缩小数组,使其仅包含数组中的活动对象。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map