19

I have variable:

var variableDynamic = 1;
// or    
var variableDynamic = 1 + i++;

Is there any way to use that to create dynamic variable names, for example something like this:

var variableName + variableDynamic = {};
// or
var (variableName + variableDynamic) = {};

I know what I wrote above is absurd, but this is to explain the idea. Is it possible?


Ok, what I want to do to create element (upload form) every time user click on add new file group, everything is working fine except that plugin that I use for it need special variable for each upload form to trigger upload button (.uploadStoredFiles();).

This is rough code I did:

    $('#addOneMoreFileOrGroup').on('click', function(){

    var latestFileUploaderId = parseInt($('.well-large .file-uploader').last().attr('id').split('-')[2]) + 1;

    $('.well-large .control-group:last').after('<div class="control-group deal-type-online">  \
        <label class="control-label">File / File Group Title:</label> \
        <div class="controls"> \
            <input class="span4 file-title" type="text"> \
            <span class="question label label-warning" data-title="File / Group Name:" data-content="Name for your file or group of related files (for example your brand logotype in different file formats)." data-original-title="">?</span> \
            <div id="file-uploader-' + latestFileUploaderId + '" class="file-uploader"></div> \
        </div> \
    </div>');

    var HERE_I_NEED_DYNAMIC_VAR = new qq.FileUploader({
        element: document.getElementById('file-uploader-' + latestFileUploaderId + ''),
        action: 'do-nothing.htm',
        autoUpload: false,
        debug: true,
        uploadButtonText: '<i class="icon icon-plus"></i> Select Files...',
        onSubmit: function() {

            $('#file-uploader-' + latestFileUploaderId + ' .qq-uploader').after('<button id="file-uploader-trigger-' + latestFileUploaderId + '" class="btn btn-primary"><i class="icon-upload icon-white"></i> Upload now</button>');

            $('#file-uploader-trigger-' + latestFileUploaderId + '').on('click', function() {

                if($(this).parent().parent().parent().parent().find('.file-title').val() !== '') {
                    HERE_I_NEED_DYNAMIC_VAR.uploadStoredFiles();
                } else {

                    $(this).parent().parent().parent().addClass('error');

                }

            });

        }
    });

});

}
ignaty
  • 535
  • 1
  • 4
  • 18
  • 1
    is an array ou tof the question? – Joseph Marikle Nov 08 '12 at 15:04
  • 1
    In what situation would you want to do this? – Kevin Brydon Nov 08 '12 at 15:04
  • So at the end I will have result of **var variableName1 = {}** or **var variableName(N+) = {}** – ignaty Nov 08 '12 at 15:04
  • I dont know how many items will be in array, they will be dynamically added. – ignaty Nov 08 '12 at 15:05
  • Duplicates: http://stackoverflow.com/questions/5117127/javascript-dynamic-variable-name, http://stackoverflow.com/questions/3935146/setting-javascript-variable-name-from-a-variable, http://stackoverflow.com/questions/8525221/programmatically-setting-the-name-of-a-variable, http://stackoverflow.com/questions/12678470/variable-name-made-of-a-variable-value – apsillers Nov 08 '12 at 15:05
  • Every duplicate: http://stackoverflow.com/search?q=%5Bjavascript%5D+dynamic+variable+names – apsillers Nov 08 '12 at 15:11
  • I am really struggling with that and think I did lost somewhere :) – ignaty Nov 08 '12 at 15:45
  • @KevinBrydon Tons of reasons. One, for example, is if you were making a mini coding thing online where users can define their own variables. – Awesomeness01 May 20 '15 at 02:31
  • http://stackoverflow.com/questions/35221108/how-to-get-random-variables-value-in-javascript/35250618#35250618 – Niklesh Raut Feb 07 '16 at 09:23

8 Answers8

32

In JavaScript, an object's properties can be access either by obj.prop or obj['prop'].

In the global scope, all variables are children of the window property. So you'll be able to do:

var variableDynamic = 'Test';
window['variableName' + variableDynamic] = 'your value';

Check out this fiddle.

However, if you'd like to limit the scope of this variable to a function, you would have to define a parent object and use this in place of window.

Connell
  • 13,925
  • 11
  • 59
  • 92
16

You can create dynamic variables with eval.

eval("dynamic" + i + " = val[i]");

Also have a look at this: Use dynamic variable names in JavaScript

Community
  • 1
  • 1
sainiuc
  • 1,697
  • 11
  • 13
5

To add to FAngels answer, you may use bracket notation anywhere. This means that in addition to using window['var'], you can use this['var'].

Awesomeness01
  • 2,321
  • 1
  • 18
  • 17
4

For this you can use eval(). But eval() is evil. You should use an array for things like this.

Example:

var i = 1337;
eval('var myvar' + i + ' = \'value\';');

alert(myvar1337);
Thomas Kekeisen
  • 4,355
  • 4
  • 35
  • 54
4

I don't think eval() is evil necessarily - it just gets misused sometimes. It's job is to take a string and "evaluate" it into JavaScript code (MDN), so iff you do need to set variables dynamically eval() is one method for doing so:

var t = 't';
var four = '4';
eval('var ' + (t + four) + ' = "some value";');
console.log(t4);

// returns "some value" to the console

There are probably better methods for effecting dynamic variable+value pairs, not least because evaluated code-strings are implemented at the global level, but the above does work. The question is, is it the best method for what you want to achieve(?). See this 2013 blog post from NCZOnline for a discussion of `eval()'.

Brian Peacock
  • 1,801
  • 16
  • 24
3

Not sure abote how that could be done in function scope, but global variable could be created like this:

window[variableName + variableDynamic] = {}
Viktor S.
  • 12,736
  • 1
  • 27
  • 52
2

Your can use eval function

var data = "anyVariableName";
eval("var temp_" + data + "=123;");
alert(temp_anyVariableName);

Or you can Use Global window object, or this:

window:

var data = "anyVariableName";
window["temp_" + data] = 123;
alert(window["temp_" + data]); //123

or using dot

var data = "anyVariableName";
window.data = 123;
alert(window.data); //123

this:

ar data = "anyVariableName";
this["temp_" + data] = 123;
alert(this["temp_" + data]); //123

or using dot

var data = "anyVariableName";
this.data = 123;
alert(this.data); //123

A Real life example:

var tasksTableNameRandom = 'tasksTable_' + Math.random().toString(36).substr(2, 5);
console.log('Tasks Table Object name: ' + tasksTableNameRandom);
this.tasksTableNameRandom = $('#tasks-data-table').DataTable({
..
});
Jaber Al Nahian
  • 903
  • 10
  • 15
0

I don't think you can create dynamic variable names in javascript, but you can set object attributes by string. So if you create your dynamic variables as attributes of an object, you can accomplish your goal.

Scott Saunders
  • 29,840
  • 14
  • 57
  • 64