Reputation: 535
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');
}
});
}
});
});
}
Upvotes: 19
Views: 76725
Reputation: 1061
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({
..
});
Upvotes: 2
Reputation: 1849
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()'.
Upvotes: 4
Reputation: 2391
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']
.
Upvotes: 5
Reputation: 1697
You can create dynamic variables with eval
.
eval("dynamic" + i + " = val[i]");
Also have a look at this: Use dynamic variable names in JavaScript
Upvotes: 16
Reputation: 14411
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
.
Upvotes: 32
Reputation: 30394
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.
Upvotes: 0
Reputation: 12815
Not sure abote how that could be done in function scope, but global variable could be created like this:
window[variableName + variableDynamic] = {}
Upvotes: 3
Reputation: 4406
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);
Upvotes: 4