简体   繁体   中英

I don't understand the syntax error in my code

my text editor does not like this piece of code I am not sure why

<script type="text/javascript">
function randmg(){
var img = [
      "banner1.png",
      "banner2.png",
      "banner3.png",
      "banner4.png"
]
var maxImg = img.length;
var randNum = Math.floor(Math.random()*maxImg)
return img[randNum]
}
</script>

It says the error is in line four "var img - ["

I thought that i was the use/placement of var under the array but I have not been able to fix it

Changed to this

function randmg(){
var img = ["banner1.png","banner2.png","banner3.png","banner4.png"];
var maxImg = img.length;
var randNum = Math.floor(Math.random()*maxImg);
return img[randNum];
}

But still having the same issue

yes, you need to add a semicolen at the end of that array.

var img = [
      "banner1.png",
      "banner2.png",
      "banner3.png",
      "banner4.png"
];

You should have semicolons and the end of each statement:

 function randmg(){
      var img = [
            "banner1.png",
            "banner2.png",
            "banner3.png",
            "banner4.png"
      ]; //here
      var maxImg = img.length;
      var randNum = Math.floor(Math.random()*maxImg); //here
      return img[randNum]; //here
 }

Although they aren't required due to legacy reasons, they are strongly encouraged. In this case the code runs, but that is no reason to omit them.

Consider this rewrite:

var randmg = (function () {
    var img = [
        'banner1.png',
        'banner2.png',
        'banner3.png',
        'banner4.png'
    ];

    return function () {
        return img[ Math.floor( Math.random() * img.length ) ];
    };
})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM