Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript not reading array items beginning with 0

Tags:

javascript

I want to give genetic algorithms a chance but I can't seem to find a solution for this problem.

This is my code:

var encodings = {
  0000: 0,
  0001: 1,
  0010: 2,
  0011: 3,
  0100: 4,
  0101: 5,
  0110: 6,
  0111: 7,
  1000: 8,
  1001: 9,
  1010: "+",
  1011: "-",
  1100: "*",
  1101: "/"
};
var chromosome = "";

for (var i = 0; i < 36; i++) {
  chromosome += Math.round(Math.random());
}

var chromArray = chromosome.match(/.{1,4}/g);

document.write(chromArray + "<br>");

for (var o = 0; o < 9; o++) {
  document.write(encodings[chromArray[o]]);
}

If you run the code, you see that there are a lot of undefineds in the output. What would cause this?

Thanks!

like image 223
JrProgrammer Avatar asked Apr 21 '16 21:04

JrProgrammer


1 Answers

You should convert the keys of the object into strings

It should be:

var encodings = 
{
  "0000": 0,
  "0001": 1,
  "0010": 2,
  "0011": 3,
  "0100": 4,
  "0101": 5,
  "0110": 6,
  "0111": 7,
  "1000": 8,
  "1001": 9,
  "1010": "+",
  "1011": "-",
  "1100": "*",
  "1101": "/"
};

var chromosome = "";

for (var i = 0; i < 36; i++) 
{
  chromosome += Math.round(Math.random());
}

var chromArray = chromosome.match(/.{1,4}/g);

document.write(chromArray + "<br>");

for (var o = 0; o < 9; o++) 
{
  document.write(encodings[chromArray[o]]);
}
like image 194
Daniel Corzo Avatar answered Oct 06 '22 05:10

Daniel Corzo