0

在过去的 6 个月里,我一直在练习 JavaScript,目前正在尝试改进我的编码方式。

我想知道的是..我是否应该为变量分配一个我将继续使用的值,即使它与我想要完成的事情无关?

在这个例子中,我一直重复使用 init_value,因为它等于 3。

        function roll_dice(){
         return Math.floor(Math.random() * init_value);
        }

       var source = ["hello.jpg","hello2.jpg","hello3.jpg", "hello4.jpg"];
       var init_value = 3;

       if( (source.length - 1) === init_value ){
         var roll = roll_dice();
         alert(roll);
       }

       for(i = init_value; i >= 0; i--){
        alert(source[i]);
       }
4

2 回答 2

2

不要那样做。给你的变量起有意义的名字,并将它们用于它们的设计。没有任何理由考虑重用变量,除非您在有限的硬件(例如嵌入式系统)上进行开发。

一个示例(只是一些与您的代码具有相同精神的模拟代码):

 var max_users = 10;
 var max_connections = 10;

 if (connections == max_connections) {
      alert("No more connections allowed!");
 }

 if (users == max_users) {
      alert("Maximum number of users reached.");
 }

即使数字相同,我也不会重复使用相同的变量。在这种情况下,我也不会创建像ior这样的变量max_connections_or_users,除非那是我想要的。

于 2013-02-23T15:00:55.310 回答
2

让我们看看如果您选择变量只是为了它们的值会是什么样子:

    var superman = 1,
    marypoppins = 0,
    mario = 3;

    function roll_dice(){
     return Math.floor(Math.random() * superman * mario );
    }

   var source = ["hello.jpg","hello2.jpg","hello3.jpg", "hello4.jpg"];
   var init_value = mario + superman * marypoppins;

   if( (source.length - superman) === mario + marypoppins ){
     var roll = roll_dice();
     alert(roll);
   }

   for(i = init_value; i >= marypoppins * mario; i--){
    alert(source[i]);
   }

仍然认为重用变量很酷吗?

于 2013-02-23T15:11:27.257 回答