2016-09-28 106 views
1
function guid (l) { 
    if(l === undefined){ 
     l = 32; 
    } 
    var ascii = ''; 
    for(var x=0; x<l; x++){ 
     var rnd = Math.floor(Math.random()*(122 - 48))+48; 
     var convert = String.fromCharCode(rnd); 
     if(!(convert.match(/[a-zA-Z0-9]/g))){ 
     // how to return 'rnd' until the lenght of the parameter is complete 
     }else{ 
      ascii += convert; 
     } 
    } 
    return ascii; 

} 
console.log(guid()); 

這是我的代碼。你能告訴我如何執行我的if語句嗎?我的輸出現在基於rnd通過if語句的次數。如果在for循環中返回

回答

0

您應該使用,而對於

var rnd = Math.floor(Math.random()*(122 - 48))+48; 
var convert = String.fromCharCode(rnd); 

while(!(convert.match(/[a-zA-Z0-9]/g))) { 
    rnd = Math.floor(Math.random()*(122 - 48))+48; 
    convert = String.fromCharCode(rnd); 
} 
+0

Thak你非常:) –

0

你可以使用一個while循環和檢查的ascii長度。

function guid (l) { 
 
    var ascii = '', convert; 
 
    l = l || 32; 
 
    while (ascii.length < l) { 
 
     convert = String.fromCharCode(Math.floor(Math.random() * (122 - 48)) + 48); 
 
     if (convert.match(/[a-zA-Z0-9]/g)){ 
 
      ascii += convert; 
 
     } 
 
    } 
 
    return ascii; 
 

 
} 
 
console.log(guid());

+0

非常感謝你:) –