简体   繁体   English

我不理解代码中的语法错误

[英]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 - [" 它说错误在第四行“ var img-[”

I thought that i was the use/placement of var under the array but I have not been able to fix it 我以为我是var在数组下的使用/放置,但我无法修复它

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 ) ];
    };
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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