0

I want to look for a variable and change its value, input is an string .

Ex. if input string is "variableSalary", I want to find if any variable defined with same name, if variable exists change its value with some other string input

vinod sahu
  • 67
  • 12
  • use eval. eval("typeof " + "thisvariableexists") will return "string" and another eval for the update.. eval("typeof" + "thisonedoesnt") will give "undefined" – amdixon May 18 '15 at 12:34
  • If I understand your question correctly, it is answered here: http://stackoverflow.com/questions/5613834/convert-string-to-variable-name-in-javascript – Sylvia Stuurman May 18 '15 at 12:36

2 Answers2

1

In javascript, all global variables are properties of the global object.
You can access properties in two ways: object.property or object["property"].
You should, in most cases, go for the first one. But the square brackets notation has one behavior the dot notation doesn't have: It allows you to search for properties that you don't know the name previously, or that will be generated dynamically. Which is what you want.

You could try this:

function isVar(string) {
  if (typeof this[string] !== 'undefined') {
    return true;
  } 
  else {
    return false;
  }
}

function changeVar(string, value, scope) {
  var scope = scope || this;
  var test = isVar.call(scope, string);
  if (test === true) {
    scope[string] = value;
    return value;
  } 
  else {
    return undefined;
  }
}

If you are checking for global variables there is no need to define the scope, but if you want to check another object you must define it. Be aware that it will not check if the variable has been declared or not, only if it has a value. So if you declared a variable but didn't define it ( var a; ), isVar will return false.

bpbutti
  • 381
  • 1
  • 8
0

You can do it like in this example: How to find JavaScript variable by its name

var a = "test";
alert(window["a"]);
window["a"] = "changed it";
alert(window["a"]);
Community
  • 1
  • 1
Thomas Theunen
  • 1,244
  • 9
  • 13