JavaScript 显示特定时间段内的数组元素



我对JavaScript相对较新,并且正在做一些练习。我正在尝试创建一个练习,其中客户评论在页面一次加载一个后显示,每次 5 秒。每个评论都是一个对象数组元素。所以我试图弄清楚如何遍历对象数组并显示每个元素 5 秒。我做了一些研究,这就是我能想到的。我甚至接近吗?

<script>
var customerReviews = {
"Denise Wilson": [
"I absolutely love this restaurant! The food is amazing. The atmosphere
is so welcoming."
],
"Russell Brown": [
"Enid's restaurant is the best place in town. Great food, nice staff
and
very clean spot."
],
"Dana Evans": [
"Came here for the 1st time and must say I'm impressed. Will definitely
be coming back. Enjoyed myself."
],
"Bilal Scott": [
"Been coming here since I was a child. Loved it then and still love it
now. The best!"
]
};
function showCustomerReviews(){
for (i = 0; i < userWord.length; i++){
setTimeout(function () { .show(customerReviews[i]); }, 5000);
}
}
</script>

.HTML

<body onload="showCustomerReviews()">
<div id="reviewsPage">
<h2>Check out Enid's Restaurant Customer Reviews below</h2>
<div id="reviewsBox">
<p>Enid's Customer Reviews</p>
<p id="displayReviews"></p>
</div>
</div>

一般来说,如果您希望某事以设定的时间间隔发生,setIntervalsetTimeout的更好替代方案。您可以启动它并让它运行,而不会遇到与for循环中的超时相关的问题。

在这里,我对您的代码进行了一些更改,customerReviews成为一个包含审阅对象的真实数组,这些对象具有审阅者的名称和审阅本身作为属性。然后是运行setInterval()并增加索引的简单问题。为了使它循环,这需要索引模组%array.length

如果你想停止它,你可以使用clearInterval

var customerReviews = [
{   
name: "Denise Wilson",
review:"I absolutely love this restaurant! The food is amazing. The atmosphere is so welcoming."
},
{   
name: "Russell Brown",
review: "Enid's restaurant is the best place in town. Great food, nice staff and very clean spot."
},
{ 
name: "Dana Evans",
review: "Came here for the 1st time and must say I'm impressed. Will definitely be coming back. Enjoyed myself."
},
{   
name: "Bilal Scott",
review: "Been coming here since I was a child. Loved it then and still love it now. The best!"
}
];
function showCustomerReviews(){
let i = 0
// set initial review
let review = customerReviews[i++ % customerReviews.length]
$('#displayReviews').text(review.name + ": " + review.review);

// change it on interval
setInterval(function(){
let review = customerReviews[i++ % customerReviews.length]
$('#displayReviews').text(review.name + ": " + review.review);
}, 5000);
}
showCustomerReviews()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="reviewsPage">
<h2>Check out Enid's Restaurant Customer Reviews below</h2>
<div id="reviewsBox">
<p>Enid's Customer Reviews</p>
<p id="displayReviews"></p>
</div>
</div>

相关内容

  • 没有找到相关文章

最新更新