1

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.

2

4 Answers 4

6

For a-z using the ASCII table and the JavaScript fromCharCode() function:

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

For 0-9:

var a = [];
for(var i=0; i<=9; i++)
{
  a.push("code" + i);
}
Sign up to request clarification or add additional context in comments.

4 Comments

Define your variables with var.
And your i variable too. for (var i...).
@Mojtaba Thanks again! I'm not an expert in JS, but I try and learn ;-)
It's also good idea to create a fiddle demo for HTML/CSS/JS answers. Here is the fiddle for your answer: jsfiddle.net/mojtaba/8ghkm
3

I'm using the unicode hexcode to loop through the whole symbols from 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);

Here goes your example.

Docs:

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

1 Comment

Thanks for the links. I need to learn more about that stuff. :)
2

you can generate array in javascript by using following code.

var arr = [];

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

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

please refer following links.

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

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

Comments

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.