1

I am writing an chess app, in that, to iterate via integer I am using,

for(var i =0; i<8; i++) { var ch = convertToCharector(i);  //using ch here...

But it would be more appropriate for me, if I do like

for(var ch='a';ch <= 'h';ch++){ // using ch directly... 

which improves readablility.

But In javascript the increment of char (in for loop ch++) is not possible, since they are not stored as integers in memory.

What Could I do to achieve this?

Whether for(var ch='a';ch <= 'h';ch++){ // using ch directly... way a direct way is not possible? Instead of using a third variable str="abcdefgh", then using str.

Muthu Ganapathy Nathan
  • 3,199
  • 16
  • 47
  • 77

3 Answers3

2

You can get pretty close by something like:

for(var ch = 'a'.charCodeAt(0); ch <= 'h'.charCodeAt(0); ch++ ) {

But if readability is all you're after, I don't know if the above helps. You might be better off with something like:

var board = { a: 0, b: 1, c: 2, d: 3, e: 4, f: 5, g: 6, h: 7 };
for(var ch = board.a; ch <= board.h; ch++) {
}

If you need a parser it could look something like this:

board.get = function(i) { return String.fromCharCode(97+i); }

...

board.get(board.a) // "a";
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
1

You could use a string defined as:

chars = "abcdefgh";

and then point to the required character in that string:

for (int i = 0; i < 8; i++) {
 canvas.drawText("" + chars.charAt(i), x, y * 30, Paint); // This draws the characters vertically
}

Good luck!

Florin Mircea
  • 966
  • 12
  • 24
0

You can define global variables like this

var _LETTERS_='abcdefgh',
    _A_=0,
    _B_=1,
    _C_=2,
    _D_=3,
    _E_=4,
    _F_=5,
    _G_=6,
    _H_=7;

and use them like that...

for(var i=_A_;i<=_H_; i++) { var j=_LETTERS_[i];
sly63
  • 305
  • 2
  • 6