所以,我试图为我的网站制作一种自动更改单词的方式,它几乎成功了,但我不知道为什么我得到“未定义”这个词;你能帮忙吗? https://imgur.com/a/yB11BTe
var words = ['affordable.', 'fast.', 'easy.', 'different.'],
element = document.getElementById('wordChange'),
currentWord = 0;
window.setInterval(function () {
currentWord++;
if (currentWord > words.length) currentWord = 0;
element.innerHTML = words[currentWord];
}, 1000);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ColorBundle | Welcome</title>
<!--BOOTSTRAP-->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<!--CSS-->
<link rel="stylesheet" href="./style/style.css">
<!--GOOGLE FONTS-->
<link href="https://fonts.googleapis.com/css?family=Odibee+Sans|Raleway&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Shadows+Into+Light&display=swap" rel="stylesheet">
<!--
font-family: 'Odibee Sans', cursive;
font-family: 'Raleway', sans-serif;
font-family: 'Shadows Into Light', cursive;
-->
</head>
<body>
<div class="nav">
<div class="nav-brand">
<h1>ColorBundle</h1>
</div>
<label for="toggle">☰</label>
<input type="checkbox" id="toggle">
<div class="menu">
<a href="#">HOME</a>
<div class="menu-mobile-border"></div>
<a href="#">ABOUT</a>
<div class="menu-mobile-border"></div>
<a href="#">WORKS</a>
<div class="menu-mobile-border"></div>
<a href="#">SERVICES</a>
<div class="menu-mobile-border"></div>
<a href="#">BLOG</a>
<div class="menu-mobile-border"></div>
<a href="#">CONTACT</a>
<div class="menu-mobile-border"></div>
</div>
</div>
<div class="top-img">
<h2><span id="wordChange">creative.</span></h2>
</div>
<script src="./script/changeword.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</body>
</html>
你能帮我解决这个问题吗?我知道这没什么大不了的,但我很好奇什么来自
最佳答案
你遍历数组,所以索引从 0 开始。而 words.length
给你索引+1
所以你的 currentWord > words.length
超出了范围。
执行 if (currentWord >= words.length)
关于javascript - 为什么我在运行 changeword.js 时会得到未定义的字样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58976647/