Javascript变量未定义

Javascript variable is undefined

本文关键字:未定义 变量 Javascript      更新时间:2023-09-26
<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>

我遇到的问题是我的计数器变量在函数中是未定义的。例如,当我调用函数preImg时,它会警告我未定义(当它应该只是0时),当它应该是3时,第二个警报显示NaN。为什么我的函数不能识别我的"var计数器",它是全局的,不是吗?你认为变量mypics也会发生同样的情况吗?谢谢!

new Array[3];
应该

new Array(3);

而是使用方括号符号来创建数组(也不需要指定长度):

var myPics = [];
你可能会问为什么要使用这种语法?原因有很多:
  1. []是一种更快更短的创建数组的方式。
  2. Array构造函数可以被覆盖,而像这样的语法构造函数不能被覆盖。
  3. 在代码中更容易发现,使调试更容易。
  4. 它有能力采取一个单一的元素(即[5]),而不是解释为数组的长度,一个常见的问题与繁琐的Array构造器。

var myPics = new Array[3];应为var myPics = new Array(3);

JsFiddle: http://jsfiddle.net/cbJAc/

element, picscounter上使用闭包的简单幻灯片对象:

function Slideshow(element, pics) {
    var counter = 0;
    this.nextImg = function () {
        element.src = pics[counter];
        counter = (counter + 1) % pics.length;
    }
    this.nextImg(); // init
}

用法:

var show = new Slideshow(
    document.getElementById("coloredImg"),
    ["./img/blue.png", "./img/red.png", "./img/yellow.png"]
);
show.nextImg(); // red
show.nextImg(); // yellow
show.nextImg(); // blue

闭包确保在定义函数时在作用域中的每个变量在调用(或再次调用)函数时仍然在作用域中。这个标准的JavaScript技术优雅地解决了你的counter问题。

使用基于模的计算可以让计数器重复序列0,1,2(在本例中)。


编辑:假设您希望每三秒切换到一个新图像:

setInterval(show.nextImg, 3000);