好的编程,我应该重用价值观吗?

时间:2013-02-23 14:56:17

标签: javascript

我在过去的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]);
       }

2 个答案:

答案 0 :(得分:3)

不要那样做。为变量提供有意义的名称,并将它们用于设计的内容。除非您在有限的硬件(例如嵌入式系统)上进行开发,否则没有任何理由考虑重复使用变量。

一个例子(只是一些与你的代码完全相同的模拟代码):

 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.");
 }

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

答案 1 :(得分: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]);
   }

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

相关问题