2013-05-16 57 views
2

我想在jQuery/JS中生成一個包含「代碼」+ [0-9]或[a-z]的數組。 所以它看起來像那樣。生成數組Javascript

編碼0,編碼1 ...,CODEa所,codeB

唯一的工作方式,現在是把它們手工編寫,我相信這是一個愚蠢的方式,有一種方法可以自動生成這一點。

如果你給一個參考文獻的答案,我可以學習如何做類似的東西,我將不勝感激。

謝謝。

+3

你可以使用for循環和的Array.push()... –

+0

看到這個帖子... HTTP:/ /stackoverflow.com/questions/4011840/create-dynamic-array-with-jquery – Pank

回答

6

對於使用ASCII table和JavaScript fromCharCode()功能A-Z

var a = []; 
for(var i=97; i<=122; i++) 
{ 
    a.push("code" + String.fromCharCode(i)); 
} 

對於0-9:

var a = []; 
for(var i=0; i<=9; i++) 
{ 
    a.push("code" + i); 
} 
+1

用'var'定義你的變量。 – 2013-05-16 07:18:44

+0

@Mojtaba謝謝! :-) – Alexxus

+2

而你的'我'變量也是。 '爲(var我...)'。 – 2013-05-16 07:20:56

3

我使用Unicode以十六進制編碼通過循環整個符號從0-Z:

var arr = []; 
for (var i = 0x30; i < 0x7b;i++){ 
    // skip non word characters 
    // without regex, faster, but not as elegant: 
    // if(i==0x3a){i=0x41} 
    // if(i==0x5b){i=0x61} 
    char = String.fromCharCode(i); 
    while(!/\w/.test(char)){char = String.fromCharCode(i++)}; 
    // generate your code 
    var res = "code"+char; 
    // use your result 
    arr.push(res); 
} 
console.log(arr); 

這裏去your example

文檔:

Unicode Table
for loop
fromCharCode
JS Array and it's methods

+0

感謝您的鏈接。我需要更多地瞭解那些東西。 :) –

1
a = []; 
for(i = 48; i < 91; i++) { 
    if (i==58) i = 65 
    a.push("code" + String.fromCharCode(i)); 
} 

alert(a.join(',')) // or cou can print to console of browser: console.log(a);