Javascript eval() and dinamically adjusting variables

Jun 23, 2017

I have a situation where I need to dinamically set variables. 

I want to set variables to strings in order those are choosed. For example: If user clicks first button var1 changes to value of specific string. If second button is clicked before other buttons, var1 changes to its value of string.

I've found out that those things are possible in javascript through eval() function but when I use it in Articulate it returns "undefined".

Let me know if there is other way of doing the same thing.

This was the way I used it:

var player = GetPlayer();
var n = player.GetVar("n_id"); //n_id is set by button click

var str1 = player.GetVar("str1"); //str1 is already defined as some string
var str2 = player.GetVar("str2"); //just like str2 and so on..
var p = eval('str' + n_id); //this line sets p to the value of str1 or str 2 or any other //depending on n_id

alert(p); // returns undefined
1 Reply
Martin Garnett

Hi Luka,

I'm familiar with code and can get around it, but I am no means a javascript expert so please excuse me if I'm miles off.

I'm not sure what's happening here:

var p = eval('str' + n_id); //this line sets p to the value of str1 or str 2 or any other //depending on n_id

Should it be:

var p = eval('str' + n); //this line sets p to the value of str1 or str 2 or any other //depending on n_id

as n is the variable you're defining at the top?

Also, you're setting the var's for str1 and str2, but you never use them?

After all of this, however, I'm still not 100% sure what you're trying to achieve? There could be a far simpler way. Could you expand on your example or put together a .story file for me to see what you're trying to do?

This discussion is closed. You can start a new discussion or contact Articulate Support.