0

I want to be able to pass a string into a function, concatenate it with a common suffix, and use that new string as an existing variable. For example,

var firstInfo = "The first string says this.";

var secondInfo = "The second says that.";

updateInfo(arg)
{
    console.log(arg + "Info");
}

updateInfo("first");
/* Should print "The first string says this.", but instead does nothing. */

What am I doing wrong? This is plain javascript, but I am open to other libraries.

Naltroc
  • 989
  • 1
  • 14
  • 34

4 Answers4

1

You need to use window[arg + "Info"] to get a value of global variable:

console.log(window[arg + "Info"]);

Here is a full fiddle

Selman Genç
  • 100,147
  • 13
  • 119
  • 184
0

It should be

updateInfo(arg)
{
    firstInfo = arg + "Info";
    console.log(firstInfo );
}

    updateInfo(firstInfo );
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

Use javascript function eval() , here's the doc

var firstInfo = "The first string says this.";

var secondInfo = "The second says that.";

function updateInfo(arg)
{
    console.log( eval(arg + "Info") );
}

updateInfo("first");
Kevin Yan
  • 1,236
  • 11
  • 19
  • Before when I was reading about eval(), it had such a bad rap that I did't want to try it. But you have proved it to be the correct solution in this case. – Naltroc Apr 14 '17 at 02:30
0

Your "firstInfo" variable is defined in the global scope, and is hence attached to window object. If you console it in the function scope without the window reference it will be invoked with the local scope.

Try this I have used the window object.

var firstInfo = "The first string says this.";

var secondInfo = "The second says that.";

function updateInfo(arg)
{
    console.log(window[arg + "Info"]);
}

updateInfo("first");
dattebayo
  • 1,362
  • 9
  • 4