为什么s不被覆盖为全局变量?

时间:2016-01-19 01:36:43

标签: javascript

randomsub是通过未显示的随机数生成的,并且是一个全局变量。这首歌没有歌名。 (可能是一个错误)正在被函数

中的s =显示而不被覆盖



<script type="text/javascript">
    var s = "No song name for this song. (May be an error)";
    var l = randomsub;
        function Name(){
           
                if (l == 0){
                   
                    s = "Tobu - Seven";
                }
                if (l == 1){
                   
                    s = "Tobu - Colors";
                }
                if (l == 2){
                   
                    s = "Tobu - Candyland";
                }
                if (l == 3){
                   
                    s = "Tobu - Such Fun";
                }
                if (l == 4){
                   
                    s = "Tobu - Dreams";
                }
        }
   
   
</script>
<font color="red"><p id="song"><p></font>
<script>
song = document.getElementById("song");
song.innerHTML = s;
</script>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:3)

您永远不会调用您的函数Name

在最后一行之前添加Name();s将被覆盖

<script>
  song = document.getElementById("song");
  Name();
  song.innerHTML = s;
</script>

当你需要像你一样做很多if语句/ switch-case语句时,也可以考虑使用对象作为哈希映射。您的代码可以重写为:

function Name() {
   var names = {
     0: "Tobu - Seven",
     1: "Toby - Colors",
     2: "Tobu - Candyland",
     3: "Tobu - Such Fun",
     4: "Tobu - Dreams"
   }

   if (l in names) {
      s = names[l]
   }
}

这样可以更轻松地添加新选项,例如5: "Tobu - Horrors"