简体   繁体   English

Java脚本-给定字符串输入,查找是否存在同名变量,变量是否存在更改值

[英]Java script - given an string input, find if there is a variable with same name, if variable exist change value

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 如果输入字符串是“ variableSalary”,我想查找是否有任何用相同名称定义的变量,如果变量存在,则用其他一些字符串输入更改其值

In javascript, all global variables are properties of the global object. 在javascript中,所有全局变量都是全局对象的属性。
You can access properties in two ways: object.property or object["property"]. 您可以通过两种方式访问​​属性:object.property或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. 因此,如果您声明了一个变量但未定义它(var a;),则isVar将返回false。

You can do it like in this example: How to find JavaScript variable by its name 您可以像以下示例一样进行操作: 如何通过其名称查找JavaScript变量

 var a = "test"; alert(window["a"]); window["a"] = "changed it"; alert(window["a"]); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM