javascript / jquery get value of a variable [duplicate] - javascript

This question already has answers here:
Javascript "Variable Variables": how to assign variable based on another variable?
(3 answers)
Closed 9 years ago.
In javascript, the way to declare a var is: var msg = 'hello', and it is simply to call msg will get the value of 'hello'
if I am now have a number of var, e.g. msg_1, msg_2 ... msg_n would there be a way to get the value by calling something like
for (var i = 0; i < n; i++)
{
var var_name = 'msg_' + i;
alert (var_name)?
}

DEMO
for (var i = 0; i < 5; i++) {
var var_name = 'msg_' + i;
window[var_name] = i;
console.log(window[var_name]);
}

You should put the values inside an array.
var messages = ["first", "second", "third"];
for (var i = 0; i < n; i++)
{
alert (messages[i])
}

I would suggest use to use array instead of what you are doing.
var myVarialbes= [];
for (var i = 0; i < n; ++i) {
myVarialbes[i] = "some stuff" + i;
}

Here you got a simple method:
var var_name=''; //declare variable only once
for (var i = 0; i < 5; i++) //You should change 5 to n
{
var_name = 'msg_' + i;
alert (var_name.split('_')[1]);
}

function do_test(){
var v1 = "variable 1";
var v2 = "variable 2";
var v3 = "variable 3";
for (i=1;i<4;i++){
var o = eval("v"+i); // you actually need this
alert (o);
}
}
But why don't you use arrays?

Related

Push object in Javascript

I need to push object to array in Javascript, but every time push overwrite the same object I have had already added. For example:
//This is object list
var NewIssue = {};
//This is array
var newIssueList = [];
function myFunction() {
for (var i = 0; i < 3; i++) {
NewIssue.Id = i;
NewIssue.Number = 233 + i;
NewIssue.Name = "Test" + i.toString();
newIssueList.push(NewIssue);
}
}
In the end I will have newIssueList with 3 same objects. Why it does overwrite the first and how to solve this problem?
You have to move the object inside the loop.
var newIssueList = [];
function myFunction() {
for (var i = 0; i < 3; i++) {
var NewIssue = {};
NewIssue.Id = i;
NewIssue.Number = 233 + i;
NewIssue.Name = "Test" + i.toString();
newIssueList.push(NewIssue);
}
}
myFunction();
console.log(newIssueList);
And then you could just extend the object literal a but to make it much more readable:
for (var i = 0; i < 3; i++) {
var NewIssue = {
Id:i,
Number:233+i,
Name:"Test"+i
};
newIssueList.push(NewIssue);
}
You can also avoid using a superfluous var by creating an inline object:
newIssueList.push({
Id: i,
Number: 233 + i,
Name: "Test" + i.toString()
});
There is only one object, and each time you push it into the array, you push a reference to the existing object. When you change the object, every element in the array reflects this, as they all point to the same object.
You need to create a new object on every iteration.
//This is array
var newIssueList = [];
function myFunction() {
for (var i = 0; i < 3; i++) {
newIssueList.push({
id: i,
number: 233 + i,
name: "Test" + i.toString()
});
}
}
myFunction();
console.log(newIssueList);

Arrays inside an array Javascript [duplicate]

This question already has answers here:
How to check if object property exists with a variable holding the property name?
(11 answers)
Closed 5 years ago.
I want to make an array so that it contains some identity name and for each of those names there is another array associated. My approach is like,
for (var i = 0; i < 10; i++) {
for (var x = 0; x < 5; x++) {
var data = someServiceCall(i, x);
var identityName = i + '-' + x;
myArray[identityName] = data;
}
}
after executing this i get something like,
[1-1: Array(8), 1-2: Array(10), 1-3: Array(10), 1-4: Array(10),.. etc]
the next time I call this function I need to check whether 1-1 exists and if yes I need to get the list related to 1-1. How can I do this..? if 1-1 is not in the myArray I will call some other function.
To check if the element having the 1-1 key exists just do:
if("1-1" in myArray)
Then to access the array associated with 1-1 use:
myArray["1-1"]
Try this. It inserts an object containing the identity name and data in each array element.
var myArray = [];
for (var i = 0; i < 10; i++) {
for (var x = 0; x < 5; x++) {
var data = someServiceCall(i, x);
var identityName = i + '-' + x;
var objectInArr = {
'identityName': identityName,
'data' : data
};
myArray.push(objectInArr);
};
};
try like this
myArray["1-1"] != undefined
Check if key exists in your array or not and act accordingly. Following is a working code snippet
var myArray = [];
for (var i = 0; i < 10; i++) {
for (var x = 0; x < 5; x++) {
var identityName = i + '-' + x;
myArray[identityName] = [1, 2];
}
}
var key = "0-0";
if(myArray[key])
console.log(myArray[key]);
you can check your array lenght and if the array is empty you will know that you need to call another action as you say. something like below might work for you
if (myArray.length === 0) {
//Call another function}
else {
//Somthing else}

Double Dimensional Array in Javascript Returning Undefined Array [duplicate]

This question already has answers here:
Javascript two dimensional arrays [duplicate]
(6 answers)
Closed 8 years ago.
I have searched alot and cannot get a clear answer to my problem.
var rowCount = 3;
var myCounter = 0;
var myNewArray = new Array();
for (var i = 1; i < rowCount; i++) {
try {
myNewArray[myCounter][0] = i;
myNewArray[myCounter][1] = i;
myCounter = myCounter + 1;
} catch (err) {
alert(err.message);
}
}
it is giving and exception saying myNewArray[myCounter] is undefined. Any idea why? I have seen other post and all have shown to declare the array like this or with new Array([]). Nothing is working.
Need help, in advance thank you.
Currently myNewArray is an array but the elements you are trying to access in it do not yet exist (undefined) so you would need to set these elements as arrays
var rowCount = 3;
var myCounter = 0;
var myNewArray = new Array();
for (var i = 1; i < rowCount; i++) {
try {
//set this element as an array if you want to then access it as an array
myNewArray[myCounter] = [];
myNewArray[myCounter][0] = i;
myNewArray[myCounter][1] = i;
myCounter = myCounter + 1;
} catch (err) {
alert(err.message);
}
}

initialize variable repeatedly using for loop in javascript

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!

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