javascript - 如何使这个javascript数组值循环并在最后一个索引处停止
问题描述
我有这个脚本,它从 javascript 数组中一次计算一个值,但问题是当它计数到最后一个索引时,它再次从索引 0 开始,但我希望它在最后一个索引处停止。我正在使用 setInterval 使其继续运行。到目前为止,这是我的代码:感谢您的宝贵时间。谢谢
<!DOCTYPE html>
<html>
<head>
<title>my page</title>
</head>
<body>
<h4>Counter</h4>
<span id="disp"></span>
<script>
var title = ['$0', '$30', '$47', '$257', '$657', '$1389', '$1557', '$2557'];
var i = 0; // the index of the current item to show
setInterval(function() { // setInterval makes it run repeatedly
document
.getElementById('disp')
.innerHTML = title[i++]; // get the item and increment i to move to the next
if (i == title.length) i = 0; // reset to first element if you've reached the end
}, 3000);
</script>
</body>
</html>
解决方案
您可以存储间隔 id,如果您完成调用clearInterval
它来停止间隔。
<h4>Counter</h4>
<span id="disp"></span>
<script>
var title = ['$0', '$30', '$47', '$257', '$657', '$1389', '$1557', '$2557'];
var i = 0; // the index of the current item to show
var interval = setInterval(function() { // setInterval makes it run repeatedly
document
.getElementById('disp')
.innerHTML = title[i++]; // get the item and increment i to move to the next
if (i == title.length) {
i = 0; // reset to first element if you've reached the end
clearInterval(interval);
}
}, 300);
</script>
推荐阅读
- javascript - 如何让 Google 的结构化数据测试工具正确评估“ratingValue”、“reviewCount”、“price”和“Product Name”?
- perl - 在 Perl 中创建链表结构
- vba - 循环浏览 VBA 中的文本文件时出现不匹配错误
- java - 调用具有输入参数数组行类型的 db2 过程的任何替代方法?
- sql - 自加入 sql 以获得状态明智的总销售额
- terraform - 从 terraform 中的数组中获取一个值,并将出现作为 terraform 中的计数
- c# - SQL 参数对象类型映射
- node.js - Populating Mongoose objects from id to new field
- java - 为什么在第一个连接结束后创建第二个连接会导致管道异常?
- ms-access - 如何在查询的 Criteria 部分的 IIF 语句中获取多个真实结果