use*_*704 3 html javascript variables
<html>
<head>
<title>Array of images</title>
<script type="text/javascript">
var myPics = new Array[3];
myPics[0] = "./img/blue.png";
myPics[1] = "./img/red.png";
myPics[2] = "./img/yellow.png";
var counter = 0;
function preImg(){
alert(counter);
if(counter == 0)
counter = 4;
counter --;
alert(counter);
document.getElementById("coloredImg").src = myPics[counter];
}
function nextImg(){
if(counter == 3)
counter = -1;
counter ++;
document.getElementById("coloredImg").src = myPics[counter];
}
</script>
</head>
<body>
<img src="./img/blue.png" id="coloredImg" alt="Image not found"/>
<input type="button" onclick="preImg()" value="Previous"/>
<input type="button" onclick="nextImg()" value="Next"/>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是我的计数器变量在函数内部未定义.例如,当我调用函数preImg时,它会使用undefined警告我(当它应该只是0时),第二个警告显示NaN时它应该是3.为什么我的函数不识别我的"var counter"它是全局的不是吗?你认为变量mypics会发生同样的情况吗?谢谢!
new Array[3];
Run Code Online (Sandbox Code Playgroud)
应该
new Array(3);
Run Code Online (Sandbox Code Playgroud)
而是使用方括号表示法来创建一个数组(也不需要指定长度):
var myPics = [];
Run Code Online (Sandbox Code Playgroud)
为什么要使用这种语法?原因有很多:
[]
是一种创建数组的更快更短的方法.Array
构造函数可以被覆盖,而像这样的句法结构不能.[5]
)并且不将其解释为数组的长度,这是繁琐的Array
构造函数的常见问题.