Dimitrij Oprčkal
Dimitrij Oprčkal

Reputation: 13

Javascript/Jquery combine text+url var to be used as array

I am making a crosswords and i am having a bit of a problem.

In jQuery I have some variables, which tells me whether the field is black or white (0,1). Each type of crosswords have different pattern.

What I would like to do is, get a var (in my case "vel") from url (the number part: 501, 502...) and combine it with text "oblika" which would tell which "oblika" which array must be used.

// Works fine

var oblika = oblika501; 

Does not work as it should (it returns string instead of "link" to the array below)

var oblika = "oblika"+vel;    
var oblika501 = [[0, 1, 1, 1, 0], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1],[1, 1, 1, 1, 1], [0, 1, 1, 1, 0]];     
var oblika502 = [[1, 1, 1, 0, 0], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1],[1, 1, 1, 1, 1], [0, 0, 1, 1, 1]]; 

Is there any workaround, or did I miss something?

Upvotes: 1

Views: 58

Answers (2)

Steve
Steve

Reputation: 3061

Store you arrays in an object like so:

var oblikaCollection = {
   501:  [],
   502:  []
};

You can then access them in your code using bracket notation:

var oblika = oblikaCollection[vel];

Upvotes: 1

AWolf
AWolf

Reputation: 8980

Yes, var oblika = "oblika"+vel; is only creating a string and not a reference to your array.

You could do it with eval (not recommended because it can also run injected code - see last console.log in the demo) or use an object so you can get your array with a string.

Please have a look at the demo below or this fiddle.

var oblika501 = [
  [0, 1, 1, 1, 0],
  [1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1],
  [0, 1, 1, 1, 0]
];

var oblika502 = [
  [1, 1, 1, 0, 0],
  [1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1],
  [0, 0, 1, 1, 1]
];

var vel = 501

var lookup = {
  oblika501: oblika501,
  oblika502: oblika502
}


var oblikaStr = "oblika" + vel

console.log('look up', vel, lookup[oblikaStr])

var oblika = eval(oblikaStr) // working but xss is a problem

console.log('Eval', oblika);

// eval example
vel = "+ console.log('injected code' + JSON.stringify(lookup))"
oblika = eval("oblika" + vel)

Upvotes: 0

Related Questions