TL;DR=我需要显示ads
数组中的一个随机对象
我有一个对象数组:
{
"ads": [
{
"adLogo": "src/img/ads/ad1.png",
"adCompany": "Ad Company 1",
"adBackgroundColor": "#1e64f0",
"adDescription": "Ad company 1 is awesome",
"adLink": "ad_company1_link_goes_here"
},
{
"adLogo": "src/img/ads/ad2.png",
"adCompany": "Ad Company 2",
"adBackgroundColor": "#1e64f0",
"adDescription": "Ad company 2 is awesome",
"adLink": "ad_compan21_link_goes_here"
},
]
}
我有这样的代码来显示JSON中的一个值:
fetch("src/js/_ads.json")
.then(function (response) {
return response.json();
})
.then(function (data) {
appendData(data);
})
.catch(function (err) {
console.log('error: ' + err);
});
function appendData(data) {
let mainContainer = document.getElementById("ad-block");
for (let i = 0; i = Math.floor(Math.random() * data.length); i++) {
let adLink = data[i].adLink;
let adDesc = data[i].adDescription;
let adLogo = data[i].adLogo;
let adCompany = data[i].adCompany;
let adBackground = data[i].adBackgroundColor;
document.querySelector("#ad-block").innerHTML +=
`
<a href="${adLink}" target="_blank" id="ad-click">
<div class="ad__banner ad__banner--dark ad__banner--column">
<div class="ad__image" style="background-color: ${adBackground}">
<img src="${adLogo}" alt="sponsored by ${adCompany}">
</div>
<div class="ad__desc">
<div class="ad__tagline">${adDesc}</div>
<div class="ad__button" style="background-color: var(--gray-700)">Start Free Trial</div>
<div class="ad__sponsored"><strong style="color: ${adBackground}">${adCompany}</strong> Affiliate</div>
</div>
</div>
</a>
`;
}
}
我有一些代码来获取一个随机值Math.floor(Math.random() *
,但它最终显示了所有的对象,而不是一个随机对象。
1条答案
按热度按时间fdbelqdn1#
不需要循环遍历数组中的所有对象,只需要生成一个随机索引并显示对象。