2017-02-17 4 views
-2

私はプロジェクトを作成してJavaScriptを学習しています。グローバル変数の理解に問題があります。この例では、私はtest()機能のスイッチパラメータに、variable = result; UB randomvariable()機能を割り当てるときには、JavaScriptでswitch文へのアクセスグローバル変数からのパラメータ値

function randomvariable() { 
    var myarray = new Array; 

    myarray = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] 
    randomvariable = Math.floor(Math.random() * 0); 
    result = (myarray[randomvariable]); 
    } 

function test() {  
    switch (result) { 
     case 0: 
     alert("haahhaha"); 
     break; 
    } 
} 

答えて

2

、あなたが関数内varで変数を宣言する場合、その変数がからアクセス可能であると動作しません。その機能だけ。 varで変数を宣言しないと、変数は(デフォルトで)グローバルになり、どこからでもアクセスできます。これは悪い習慣であり、避けるべきです。変数の宣言は、混乱を避けるために常に明示的に行う必要があります。

ここで、キャッチとは、変数を含む関数を実行して、変数の有効範囲を有効にする必要があることです。あなたの場合、実際にrandomvariable関数を実行することはないので、result = ...は実行されず、グローバル変数は作成されません。さらに、test関数を呼び出すことも決してありません。

さらに、関数の値randomevariableをランダム計算の結果に再割り当てします。それはあなたがすべきことではありません。その代わりに、関数returnを指定するか、関数に変数を設定させるだけで済みます。

// Declare result in the Global scope 
 
var result = null; 
 

 
function randomvariable() { 
 
    var myarray = new Array; 
 

 
    myarray = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]; 
 
    
 
    // This is the correct code for getting one of the array values randomly, 
 
    // but we'll comment it out here so that we can force the value of 0 for 
 
    // testing purposes 
 
    //result = (myarray[Math.floor(Math.random() * myarray.length)]); 
 
    result = 0; 
 
} 
 

 
function test() { 
 
    // Generate the random number by invoking the function that does that work 
 
    randomvariable(); 
 
    
 
    // Now, the global has a value assigned to it 
 
    console.log(result); 
 
    
 
    switch (result) { 
 
    case 0: 
 
     alert("haahhaha"); 
 
     break; 
 
    } 
 
} 
 

 
// Now, invoke test to get the whole thing working 
 
test();

彼らは同じ範囲に存在する他の変数との衝突の可能性を作成すると、このすべてを言って、グローバル変数は避けるべきです。常にコードを実行できる最小限の範囲で変数を指定してください。グローバルはバグの有名なソースです。

+0

大きな説明をいただきありがとうございます – zexurity

関連する問題