2010-03-22 81 views
0

我有以下問題。警報總是返回未定義,但我知道它有一個值。我究竟做錯了什麼。我出的解決方案......JS中的函數返回undefined

我使用jQuery jQuery的1.4.2.min.js

TNX提前

$(document).ready(function(){ 
    $('#generateButton').click(createIBAN); 
}); 

function createIBAN(){ 
    //---- First check if a bank has been selected, 
    //---- if not, then show error 
    if($('#selectBank').val()==''){ 
     alert('Selecte a bank!'); 
    }else{ 
     var bankAccount = generateBankAccount(); 
     alert(bankAccount); 
    } 
    return false; 
} 

function generateBankAccount(){ 
    //---- Create "elfproef" bankaccount 
    var bankAccount = ''; 
    //---- Set the amount of digits in a bankaccount 
    digitAmount  = 9; 
    //---- Make random digitstring 
    for (var i = 0; i < digitAmount; i++) { 
     bankAccount += Math.floor(Math.random() * digitAmount); 
    } 
    //---- validate the string, if not "elf-proef" 
    if (elfProef(bankAccount)==false) { 
     //---- regenerate the string 
     generateBankAccount(); 
    }else{ 
     return bankAccount; 
    } 
} 

function elfProef(bankAccount) { 
    //---- set sum to 0 and start the for-loop for counting 
    var sum = 0; 
    for (var i = 0; i < digitAmount; i++) { 
     //---- for every digit multiply it times 9 - number 
     //---- of the digit and count it to the sum var 
     sum += bankAccount.charAt(i) * (digitAmount - i); 
    } 
    //---- Check if sum can be devided by 11 without having ##,## 
    if(sum % 11==0){ 
     //---- return true means string is "elf-proef" 
     return true; 
    }else { 
     //---- String is not "elf-proef", try again 
     return false; 
    } 
} 

回答

7

本節:

if (elfProef(bankAccount)==false) { 
    //---- regenerate the string 
    generateBankAccount(); 
}else{ 
    return bankAccount; 
} 

如果elfProef返回false,那麼的BankAccount將永遠不會被退回。它會簡單地運行generateBankAccount,這將返回一個永遠不會使用的值。嘗試將其更改爲這樣:

if (elfProef(bankAccount)==false) { 
    //---- regenerate the string 
    return generateBankAccount(); 
}else{ 
    return bankAccount; 
} 
+0

+1對於返回函數結果 – 2010-03-22 19:57:01

+0

該死的,這對我來說很愚蠢,tnx,它有幫助。 – Megapool020 2010-03-22 21:54:58

1

我把它generateBankAccount是一個遞歸函數,對?如果這是真的,你忘記把「返回」放在嵌套調用的前面。

0

我認爲你需要改變,如果其他的generateBankAccount,內容如下:

if (elfProef(bankAccount)==false) { 
    //---- regenerate the string 
    return generateBankAccount(); 
}else{ 
    return bankAccount; 
} 

,否則你到generateBankAccount遞歸調用不會做任何事情。

0

將此:

if (elfProef(bankAccount)==false) { 
    //---- regenerate the string 
    generateBankAccount(); 
} 

成這樣:

if (elfProef(bankAccount)==false) { 
    //---- regenerate the string 
    return generateBankAccount(); 
} 

你可以考慮重寫功能,且無需遞歸:

do { 
    bankAccount = ''; 

    for (var i = 0; i < digitAmount; i++) { 
     bankAccount += Math.floor(Math.random() * digitAmount); 
    }  
} 
while (!elfProef(bankAccount)); 

return bankAccount; 

使用循環使得邏輯更簡單,它如果你在一個很大的後面無法生成一個有效的帳號,那麼它不會咀嚼堆棧空間嘗試次數。