2

I want to generate an array in jQuery/JS, which contains "code"+[0-9] or [a-z]. So it will look like that.

code0, code1 ..., codeA, codeB

The only working way now is to write them manually and I am sure this is a dumb way and there is a way to generate this automatically.

If you give an answer with a reference to some article where I can learn how to do similar stuff, I would be grateful.

Thank you.

4

4 回答 4

6

对于az使用ASCII 表和 JavaScript fromCharCode()函数:

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);
}
于 2013-05-16T07:17:24.083 回答
3

我正在使用 unicode hexcode 从 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);

这是你的例子

文件:

Unicode Table
for loop
fromCharCode
JS Array 及其方法

于 2013-05-16T07:29:26.667 回答
2

您可以使用以下代码在 javascript 中生成数组。

var arr = [];

for (var i = 0; i < 5; i++) {

    arr.push("code"+ i);
}

请参考以下链接。

https://developer.mozilla.org/en/docs/JavaScript/Reference/Global_Objects/Array

http://www.scriptingmaster.com/javascript/JavaScript-arrays.asp

于 2013-05-16T07:11:05.920 回答
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);
于 2013-05-16T07:29:59.963 回答