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);
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"
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.
I am having troubles figuring out the for condition for a javascript learning course I am doing.
I am not getting normal errors because I am doing it in the course, but the error I am receiving in the course is this...
Oops, try again. Careful: your second 'for' loop should stop when it reaches its current point in the string + myName.length.
These are the instructions:
First, you'll want to set your second loop's iterator to start at the first one, so it picks up where that one left off. If your first loop starts with
for(var i = 0; // rest of loop setup
your second should be something like
for(var j = i; // rest of loop setup
Second, think hard about when your loop should stop. Check the Hint if you get stuck!
Finally, in the body of your loop, have your program use the .push() method of hits. Just like strings and arrays have a .length method, arrays have a .push() method that adds the thing between parentheses to the end of the array. For example,
newArray = [];
newArray.push('hello');
newArray[0]; // equals 'hello'
This is my code
var text = "Hello, my name is Becky. What is your name?\
I repeat, my name is Becky. Can't you figure out that my\
name is Becky. Becky!!!!";
var myName = "Becky";
var hits = [];
for (i = 0; i < text.length; i++) {
if (text[i] === 'B') {
for (var j = i; i < myName.length; i++) {
hits.push();
}
}
}
I know the issue resides in this line:
for (var j = i; i < myName.length; i++) {
I just can't figure out exactly how I need to structure it.
UPDATE:
Final answer of question:
/*jshint multistr:true */
var text = "Hello, my name is Becky. What is your name?\
I repeat, my name is Becky. Can't you figure out that my\
name is Becky. Becky!!!!";
var myName = "Becky";
var hits = [];
for (i = 0; i < text.length; i++) {
if (text[i] === 'B') {
for (var j = i; j < (i + myName.length); j++) {
hits.push(myName);
}
}
}
if (hits === 0) {
console.log("Your name wasn't found!");
} else {
console.log(hits);
}
I'll give you the solution because you can learn more from the direct solution than from banging your head on that one.
var text = "Hello, my name is Becky. What is your name?\
I repeat, my name is Becky. Can't you figure out that my\
name is Becky. Becky!!!!";
var myName = "Becky";
var hits = [];
for (i = 0; i < text.length; i++) {
if (text[i] == 'B') {
var equal = true;
for (var j = 0; j < myName.length; j++) {
if (text[i + j] != myName[j]) {
equal = false;
break;
}
}
if(equal) hits.push(myName);
}
}
There may be other ways to reach this result. This is one of them.
Explaing what "push" does:
Arrays are lists of variables. You store a value in a variable like this:
var myNumber = 777;
var myName = "Nelson";
An array declaration looks like this:
var myNumbers = [];
then you put something inside of it, like this:
myNumbers.push(333);
myNumbers.push(555);
myNumbers.push(777);
then if you try: console.log(myNumbers), it will print: [333, 555, 777]
if you add another push:
myNumbers.push(999);
will add 999 to the list resulting in [333, 555, 777, 999]
Check this demo
got it ? take a look here to more detailed explanation:
http://www.hunlock.com/blogs/Mastering_Javascript_Arrays
Am not sure what you are trying to achieve,
Here is something may help
var text = "Hello, my name is Becky. What is your name?\
I repeat, my name is Becky. Can't you figure out that my\
name is Becky. Becky!!!!";
var myName = "Becky";
var hits = [];
for (i = 0; i < text.length; i++) {
if (text[i] == 'B') {
var res = '';
for (var j = i; j < i+myName.length; j++) {
res = res+text[j];
}
if(res == myName)
{
hits.push(myName);
}
}
}
console.log(hits);
Here is demo
I have a set of variables:
var var1 = 0;
var var2 = 0;
var var3 = 0;
var var4 = 0;
var var5 = 0;
And I want to check them all with a for Loop, but I'm not quite sure of the syntax:
for( var i = 1; i<6; i++){
alert(var[i]);
}
that for loop yields no results.
Put them in an array instead.
var vars = [0, 0, 0, 0, 0, 0];
for(var i = 0; i < vars.length; i++) {
alert(vars[i]);
}
If you're defining the varables in the global scope, you can access the values using window['var'+i]:
for(var i = 1; i<6; i++){
alert(window['var'+i]);
}
To access them you would have to use the scope to which they were written. If your code is in the window scope that would then become:
for( var i = 1; i<6; i++){
alert(window['var'+i]);
}
Though of course it's far cleaner if it's in a different scope specific to whatever you're doing. In those cases often
for( var i = 1; i<6; i++){
alert(this['var'+i]);
}
would work.
The data construct you are using is not good for this. Using an array or object is much more feasible for what you want to do as well as being easily extendable.
var arr = [0,0,0,0,0,0];
for (var i = 0; i < arr.length; i++) {
alert(arr[i]);
}
var[i] is used it var is an array. But in your case it isn't. The best way would be to place those values in an array, like;
var myvar = [0,0,0,0,0];
then use the for loop to check for the value.
for( var i = 1;i<6; i++){
alert(myvar[i-1]);
}
my question is can i possibly initialize variables repeatedly (with changing only numbers after them) this is my code
for(i = truStorage.getItem('elementCount'); i>0; i--) {
var obj = truStorage.getItem("element_" + i);
var [obj_+i] = element(erd.Entity , obj.posx, obj.posy, obj.text );}
};
basically i just want to initialize a variable like
something_i = "";
and the result will be like this
var element_1 = element(erd.Entity, 100, 200, "Employee");
var element_2 = element(erd.Entity, 100, 400, "Salesman");
var element_3 = element(erd.WeakEntity, 530, 200, "Wage");
var element_4 = element(erd.IdentifyingRelationship, 350, 190, "gets paid");
im not trying to use variables as a storage but rather to instantiate an element for a function.
This is a job for an array.
var something = [];
var somethings = 5;
for(var i = 0; i < somethings; i++) {
something[i] = "";
}
You should now be able to access the five values like this:
console.log(something[0])
console.log(something[1])
console.log(something[2])
console.log(something[3])
console.log(something[4])
Notice you use 0 to access the first element. That's just how it is because JavaScript arrays are zero-based.
This is best scenario to use array:
var counter=0,something = new Array();
for(i = truStorage.getItem('elementCount'); i>0; i--) {
something[counter] = truStorage.getItem("element_" + i).text;
counter++;
}
};
Try:
for(var i=1; i<=4; i++) {
this["something_" + i] = i;
}
console.log(something_1); //outputs 1;
console.log(something_2); //outputs 2;
console.log(something_3); //outputs 3;
console.log(something_4); //outputs 4;
Note: using an array will be faster!