简体   繁体   中英

Dynamically assigning variable names JavaScript

I am trying to dynamically assign variable names using the user's input. For example:

var input = document.querySelector('input');

for(var i = 0; i < 10; i++){
   var newVariableName = //input.value;
}

Any help would be very much appreciated.

Thank you, Scratch Cat

Everything in JavaScript is an object. The way JavaScript works, you can add properties to objects in two ways:

  1. Specify them the fixed way (eg obj.propertyName = 'Value' )
  2. Specify them using array notation (eg obj[propertyName] = 'Value' ). In this case, note that propertyName is a string value.

In both cases, the result will be exactly the same. You could retrieve those properties likewise, eg obj.propertyName and obj[propertyName] . Both will return 'Value' .

In your case, @LuudJacobs's suggestion about using the window object will most probably do the trick...

You can use array in which the keys will be the input values and the value would be anything you want.

html

<form>

<input type="text" value="demo1" class="example"><br />
<input type="text" value="demo2" class="example"><br />
<input type="text" value="demo3" class="example">

</form>

js First you declare array

var a = new Array();

Then you use for loop to assign key names to array which will be the input values

for(var i = 0; i < 3; i++){
    a[x[i].value] = x[i].value;
}

Finally you can use those key names to access the values

alert(a['demo1'] + ' ' +a['demo2'] + ' ' + a['demo3']);

Here is a link to an example https://jsfiddle.net/309fpsjn/1/

 <html> <form> <input type="text" value="demo1" class="example"><br /> <input type="text" value="demo2" class="example"><br /> <input type="text" value="demo3" class="example"> </form> <script> var x = document.querySelectorAll(".example"); var a = new Array(); for(var i = 0; i < 3; i++){ a[x[i].value] = x[i].value; } alert(a['demo1'] + ' ' +a['demo2'] + ' ' + a['demo3']); </script> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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