How to create javascript variable with other variable value in name - javascript

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] = ...;
}

Related

Generate x number of objects

A desired x number of objects is to be created.
The system creates x number of objects.
for (i = 1; i <= x; i++) {
let obj = new Object()
}
I cannot seem to figure out how this can be done without the objects having the same name. I thought that naming them obj1 to objx using iteration to avoid conflicting names is a solution. However I do not know how to name objects and variables using the iteration number as part of its name.
You are looking for an array that holds all the different objects. In your loop, you can push the object to that array:
const objects = [];
for(let i = 1; i <= x; i++) {
let obj = {};
objects.push(obj);
}
Now you can get a certain object as:
objects[5] // the sixth object
Or you can go over all objects as:
for(const obj of objects)
console.log(obj);
As I understood you would like to be able dinamically create variables with different names.
It is possible but it is bad practice because we create global variables
for (i = 1; i <= x; i++){
window['obj' + i] = {i}; //iterate name
}
after that you can call obj1, obj2, ... and they are all global
I recommend to use local object or Map
const localObj = {};
for (i = 1; i <= x; i++){
localObj['obj' + i] = {i};
}
then you just write localObj.obj1, localObj.obj2 ...
const localMap = new Map();
for (i = 1; i <= x; i++){
localMap.set('obj'+i, i);
}
To get your data: localMap.get('obj1'), localMap.get('obj2') ...

how to access instance's 'this' in collection of objects

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.

Javascript : generate variable by for loop

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.

Scope of uninitialized variable in JavaScript

I cannot understand why this code is behaving as it is:
for (var i = 1; i < 3; i++) {
var j;
if (!j) {
j = 1;
} else {
alert("why are we here? j shouldn't be defined but it's " + j);
}
}
(jsFiddle)
If I set j to null and check for null, it works the way I think it should.
This isn't how Java, C#, C++, etc. work, hence, the confusion.
This is because variables in JavaScript are scoped to functions (or the global scope if not within a function). A var is not scoped inside of a loop, and curly braces do not defined a new closure. Basically, the value of j persists after the loop body, and the var does not re-define j as undefined. This is why explicitly setting var j = null; has the expected effect.
Example 1:
A good way to think about this is, any time you declare a variable with var, like this.
function someFunc() {
for(var i = 0; i < 3; i++){
var j;
}
}
The interpreter hoist the variable declarations like so.
function someFunc() {
var i;
var j;
for(i = 0; i < 3; i++){
}
}
Notice that since the var j declaration is hoisted to the top of the function, the declaration actually does nothing within the loop.
Example 2:
However, if you were to initialize the variable with null like this.
function someFunc() {
for(var i = 0; i < 3; i++){
var j = null;
}
}
It would be interpreted like this.
function someFunc() {
var i;
var j;
for(i = 0; i < 3; i++){
j = null;
}
}
Notice how for every loop, j is set to null.
ES6 let keyword:
There is a keyword in ES6 which will create a scope in a loop like this, it is the let keyword. Keep in mind that browser support for the let keyword is poor at this point.
for (var i = 1; i < 3; i++) {
let j;
if (!j) {
j = 1;
} else {
alert("why are we here? j shouldn't be defined but it's "+ j);
}
}
The first time your for loop executes the body of the loop, j is undefined and thus your code sets j=1. On the subsequent iterations of the loop, j is already defined and set to 1 so it goes into your else clause as would be expected.
This occurs because variables defined with var in Javascript are function scoped, not block scoped and if not inside a function, then they are global. So, there is only one variable j in your jsFiddle and each iteration of the for loop uses the same variable (thus inheriting the value from the previous iteration).
It will work if you initialize j = null; inside the body of the for loop because then you're reinitializing it for each iteration rather than using the value from the previous iteration.
ES6 proposes to add the let declaration which would scope to the nearest block. See What's the difference between using "let" and "var" to declare a variable? for more info on let.
There isn't a block scope in JavaScript, only global and function scopes. Although, JavaScript variable statements are so flexible that they will give the programmer the illusion that a block scope could exist, but the truth is that variables declared in JavaScript functions are later hoisted by the interpreter. This means that their declarations are moved to the top of the most-recently declared function. Take this for example:
function test() {
console.log('a test');
for (var i = 0; i < 100; i++) {
var k = i + Math.random();
console.log(k)
}
}
The JavaScript interpreter, internally, will "transform" the code to the following:
function test() {
var i, k; // var declarations are now here!
console.log('a test');
for (i = 0; i < 100; i++) {
k = i + Math.random();
console.log(k)
}
}
It will move all the var declarations to the begining of the most recent function declaration. In your code, the hoisting will create the following code:
// A anonymous function created by jsFiddle to run your script
function () {
var i, j;
for (i = 1; i < 3; i++) {
if (!j) {
j = 1;
} else {
alert("Why are we here? j shouldn't be defined, but it's " + j);
}
}
}
The variable is undefined in the first time, then it gets assigned 1 and then your message is printed.

jQuery dynamically increment variable name inside a for-loop

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);

Categories

Resources