簡體   English   中英

為什么要使用我的功能,而使其不再起作用?

[英]Why is it taking my function and making it not a function anymore?

我有一個返回1-10隨機數的函數。 當我在其他函數中使用它時,它可以工作一次,但是隨后開始出現錯誤,提示它不是函數。 這不是確切的代碼,只是一個類似的示例代碼。 它產生一個錯誤,指出“ TypeError:對象[object DOMWindow]的屬性'ran'不是一個函數”為什么這樣做?

非常感謝

var buffer = [];

function ran() { 
   return Math.round(Math.random()*10);
};

function test(){
   var size = 6;
   for (i=0; i<=size;i++) {
      var num = ran();
      if (num === 2 || num === 3){
         buffer.push(num);
      };
   };
};

您的代碼很好,但是從錯誤看來,您似乎正在將某些值分配給隱含的全局變量ran ,該變量在代碼的其他地方ran

var buffer = [];

function ran() { 
   return Math.round(Math.random()*10);
};

function test() {
   var size = 6;
   for (i=0; i<=size;i++) {
      var num = ran();
      if (num === 2 || num === 3){
         buffer.push(num);
      };
   };
};

// ... somewhere else:

function someOtherFunction() {
   ran = 5;  // This will break your run() function when 
             // someOtherFunction() is called.
}

在這種情況下,請確保使用var關鍵字將變量的范圍限制為聲明變量的函數:

// ... somewhere else:

function someOtherFunction() {
   var ran = 5;  // This will limit the scope of ran and will 
                 // not conflict with the run() function.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM