Am I able to use for loop to declare variables? Because declaring variables with similar one by one is not smart.
For example if I want variables like: DATA1, DATA2 and DATA3, I will normally declare it like below:
var data1 = "";
var data2 = "";
var data3 = "";
And the below is what I expect we can do in the actual code.
Using for loop and using "i" to assign number for each variable.
for(var i = 0; i < 3 ;i++){
var data+i = "";
}
am I able to do that? I suppose the above code is not the correct way to do that but just a concept.
You can define Object or Global variable.
var variables = {};
for (var i = 0; i < 3; i++) {
variables['data' + i] = i;
}
console.log(variables);
// you can use it like variables.data0
// by the way you can define global variables as you want
// but note that this pollutes the global space
for (var i = 0; i < 3; i++) {
window['data' + i] = i;
}
// so you can use it like
console.log(window.data0, ' or ', data0)
Because of the fact that javascript is dynamically typed you can do something like that. JavaScript gives you the possibility of accessing variables through a key.
var baseVariable = {};
for(var i = 0; i < 3; i++){
baseVariable["data" + i] = "ValueForData" + i;
}
You can than access these variables pretty easy by iterating through the baseVariabel, or if you now the exact amount you can even call it like that:
baseVariable.data1
You can use eval function to evaluate code from string.
For example:
var a = 2; eval('alert(a)');
Take a look at assignment chain. May be is would be suitable.
var a = b = c = d = e = f = g = "";
But this ways is not a good practice.
As mentioned in comments for your question better way to use array or object to store data.
Related
I am trying to combine a string and number to a dynamiclly generated variable.
Currently tried it this way:
const ElementCount = 2;
for (i = 1, i <= ElementCount, i++) {
let SampleVariable[i] = "test";
}
ElementCount will later on be dynamic.
The result of the above function should look like this:
SampleVariable1 = "test"
SampleVariable2 = "test"
My code seems to be wrong - what do I have to change here?
Solution can be native JS or jQuery as well.
Thanks a lot!
solution is to use eval, but It's nasty code, Avoid using 'eval', just use an array or object.
1, eval solution:
const ElementCount = 2;
for (let i = 1; i <= ElementCount; i++) {
eval("let SampleVariable[" + i + "] = 'test'");
}
2, array solution:
const ElementCount = 2;
let Variables = []
for (let i = 1; i <= ElementCount; i++) {
Variables["SampleVariable" + i] = "test";
}
3, object solution:
const ElementCount = 2;
let Variables = {}
for (let i = 1; i <= ElementCount; i++) {
Variables["SampleVariable" + i] = "test";
}
There are few mistakes in your code
You using comma , to separate the statements. You should use semicolon ;
You are declaring SampleVariable inside the for loop so its not avaliable outside. Declare it outside the loop.
You shouldn't use independent variable for this purpose as they just differ by 1. You should store them in array and use SampleVariable[number] to access them.
You should initialize i = 0 otherwise the first element of SampleVariable will be undefined
const ElementCount = 2;
let SampleVariable = [];
for (let i = 0; i < ElementCount; i++) {
SampleVariable[i] = "test";
}
console.log(SampleVariable);
This is my solution
const ElementCount = 2;
for(i = 1; i <= ElementCount; i++) {
this['SampleVariable'+i] = "test";
}
SampleVariable1 // "test" (browser)
this.SampleVariable2 // "test"
I have created a object with constructor function. Then I stored it's 'this' value to a variable.
after creating few objects using 'new' I pushed them to an array. When I access the objects again, all the objects' 'this' value has become the last object created.
var t = function(x){
j = this;
this.u = x;
this.k = function (){
return j.u;
}
}
var g = [];
for(var i = 0; i < 10; i++)
g.push(new t(i));
for(var i = 0; i < 10; i++)
console.log(g[i].k());
this prints ten '9's instead of 0 to 9.
How can I access current instance's 'this' inside function. and access current object's details.
Cause j is a global variable. Do:
let j = this;
So then its part of thr closure.
Use var to localize j's scope
var j = this;
Demo
var t = function(x) {
var j = this;
this.u = x;
this.k = function() {
return j.u;
}
}
var g = [];
for (var i = 0; i < 10; i++)
g.push(new t(i));
for (var i = 0; i < 10; i++)
console.log(g[i].k());
Otherwise, since j's scope is not localized to t, it's last value 9 is returned when you invoke k().
As the previous answers mentioned, you need to use var or let keywords, otherwise the j variable will be bounded to global scope.
var j = this;
One more thing to add, to prevent this kind of mistakes, you can specify:
'use strict'
at the top of your file which will inform you about this mistake by throwing an error your way. Using strict mode prevents you from accidentally binding variables to global scope.
I want to create new variables in a for-loop where the variable-name shall contain the index of the loop: pos_1, pos_2...
So I try that:
for(i=1; i<=slide_length;i++){
var pos_[i] = 49*i;
}
But that doesn't create anything. What do I do wrong here?
You can use window["variable_name"] to create global variables.
var slide_length = 5;
for(i=1; i<=slide_length;i++){
window["pos_"+i] = 49*i;
}
console.log(pos_5);
create the array outside the loop.
var pos_ = []
for(i=1; i<=slide_length;i++){
pos_.push(49*i);
}
then pos_ has your values after the loop.
You should use an array:
function createVariables(){
var pos = [];
for (var i = 0; i <= slide_length; ++i) {
pos[i] = 49*i;
}
return pos;
}
You then have access to pos[0] through pos[slide_length].
Following code will be useful to you,
var slide_length = 10;
for(i=1; i<=slide_length;i++){
this['pos_'+i] = 49 * i;
}
console.log(pos_1);
console.log(pos_8);
console.log(pos_10);
Hi I need to create a load of variables in a javascript loop so say my loop goes round 5 times starting at 0 by the end of it the following variables should be defined:
variable_0
variable_1
variable_2
variable_3
variable_4
Can anyone tell me how to do this please?
This will create "global" variables by registering them on the window object:
for (var i = 0; i != 5; ++i) {
window['variable_' + i] = null;
}
It's not really nice to do that though =/ a better way is to define an object in which you create dynamic properties.
var obj = {}
for (var i = 0; i != 5; ++i) {
obj['variable_' + i] = null;
}
console.log(obj.variable_0); // null
Why not just use an array:
var variable = [];
If you really want to create 5 variables, you need to choose the scope of them, the easiest is probably window, then you can use the sqare bracket syntax:
for(var i=0;i<5; i++){
window["variable_" + i] = 0; // or anything really!
}
Now the following variable is available:
window.variable_1 = 123
You can only create variably named variables as part of an Object:
obj['variable_' + i] = value;
There's no equivalent for function scoped variables, although you can of course do:
function foo() {
var obj = {};
for (var i = 0; ... ) {
obj['variable_' + i] = value;
}
}
You can fake global variables (but shouldn't) by using the window global object in place of obj, as shown by #Jack.
Of course in most circumstances (and since you're using numbers to differentiate the variables) what you should really do is use an array:
var myvar = [];
for (var i = 0; i < n; ++i) {
myvar[i] = ...;
}
is it possible to add i to a var inside a for-loop?
in wrong syntax it would look like the code below
for(i=1; i<=countProjects; i++){
var test + i = $(otherVar).something();
};
Thanks!
It would be best to use an array for this:
var test = [];
for (i = 1; i <= countProjects; i++) {
test[i] = $(otherVar).something();
};
Then you could access the values like this:
console.log(test[1]);
console.log(test[2]);
etc...
If you have really good reason to have named variables for each value, you can create them like this:
for (i = 1; i <= countProjects; i++) {
window["test" + i] = $(otherVar).something();
};
console.log(test1);
As Mat stated, you should be using arrays for this type of functionality:
var projects = [];
for (var i = 0; i <= countProjects; i++) {
projects.push($(otherVar).something());
}
You could craft variable names, using object["varname"] syntax. But it's _generally_ bad practice:
var varName;
for (var i = 0; i <= countProjects; i++) {
varName = "test" + i.toString();
this[varName] = $(otherVar).something();
}
console.log(test1);