1

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?

1

2 Answers 2

1

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];
Sign up to request clarification or add additional context in comments.

Comments

0

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)

1 Comment

I like this, but xss is a problem ye.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.