This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 8 years ago.
I need to set a local variable inside a for loop in a function, but part of the name of this var needs to be a string, more specifically an array index.
See the example:
function MyFunction () {
var strings = ["first","second","third","fourth"];
for (var i = 0; i < strings.length; i++) {
var "My_" + strings[i] + "_var" = "Hi, I'm the " + strings[i] + " var!";
}
}
I know this is not the correct way, I'm just illustrating what I want to do. I've already tried using window[] or this[], but seems like the var becomes global.
A way is using objects you can make the object's variable name a string using bracket notation
var obj = {};
var name = ['first'];
obj[name[0]]='whatever';
Last but not a secure way is using:
eval('var '+name+' = '+value+';');
Eval evaluate the string as a javascript command therefore you can make up your variables with their names made dynamically.
Related
This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 1 year ago.
I'm trying to add a variable into a path like this:
response.response.body.result.company.data.t${variable}.month_col_val[i]
I know it's wrong, yet I'm not being able to find if it's actually posible to do it and how to do it.
My json file contains objects named t0, t1, t2... and so on inside data, so i'm trying to get an specific one by adding the variable value along the T
Variable is define outside the fuction and pass as a parameter.
for (let o = 0; o < 12; o++) {
cy.get($el).find('.month-data-cols').eq(o).invoke('text').then($text => {
let monthGross = $text
let monthGrossReq = response.response.body.result.company.data.t${variable}.month_col_val[o]
monthGross = monthGross.toString().replace(/,/g, '').trim();
expect(monthGross).to.include(monthGrossReq);
})
};
Try using square-bracket notation instead of dot-notation at that property
const data = response.response.body.result.company.data
const monthGrossReq = data[`t${variable}`].month_col_val[o]
This question already has answers here:
Use dynamic variable names in JavaScript
(19 answers)
Closed 3 years ago.
I have a list of 3 lines. I want to efficiently separate each line out as it’s own individual item.
myList = [MultiLine.attributes.renderers[0], MultiLine.attributes.renderers[1],
MultiLine.attributes.renderers[2]]
What I want:
line1 = MultiLine.attributes.renderers[0];
line2 = MultiLine.attributes.renderers[1];
line3 = MultiLine.attributes.renderers[2];
I know in Python there is the casting function which I would use like so:
line + str(i) = MultiLine.attributes.renderers[i];
However I'm getting ReferenceError: invalid assignment left-hand side with the equivalent JS:
for(var j = 0; j < myList.length; j++){
"line" + String(j) = MultiLine.attributes.renderers[j];
}
Any ideas?
I don't know how to properly go about changing the value of my variable within the for-loop. Would Break statements help?
You could use a destructuring assignment with the array.
var [line1, line2, line3] = MultiLine.attributes.renderers;
This question already has answers here:
Use dynamic variable names in JavaScript
(19 answers)
Closed 8 years ago.
I have a javascript variable
var varNameValue = "Name";
Now i want to create another variable using the value of varNameValue inside the name of the Other
var x(varNameValue)y = "abc";
So that my new variable name becomes
var xNamey = "abc";
Is there any way to do it. Please help.
Not directly in JavaScript. If you know the content in which it is run, then you can. For example, if this is in a browser, and it is in the global context (which maps to window), then you could do
window["x"+varNameValue+"y"] = "abc";
Similarly if it is on an object
var obj = {};
obj["x"+varNameValue+"y"] = "abc";
But just as a standalone var without any context? Nah.
var varNameValue = "Name";
eval("var x" + varNameValue + "y = 'abc';")
alert(xNamey);
Try
var obj={}
var nameValue="Name";
obj["x"+ nameValue +"y"]= "abc"
Then you can access it using obj.xNamey
This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 8 years ago.
Problem with example:
Variable name: var product5519 = 10;
I can get this name in the form of a String i.e
var str = "product5519"
Is there any way to convert it into variable name so that i can use the value assigned to
product5519
I know one way to solve this problem i.e using eval(str)
If there is any another way to solve it please tell?
Once you are certain creating a global variable was the Right Thing to do, you can add your variable to the window object, like so:
window[str] = 42;
This works because variable lookups end up trying the window object if the variable was not defined in an inner scope.
It's a bit hacky but if you wanted to make a global variable you could do:
var str = "product5519";
window[str] = value;
You could then access the variable like:
window[str];
window.str;
str; // Assuming that there is no local variable already named "str"
you could do something like:
window['product5519'] = 'value'
it may be better to have an array of products, depending on the situation ofc.
You can use an associative array:
var variables = [];
variables['product5519'] = 10;
console.log(variables['product5519']);
This question already has answers here:
Is there a way to access a javascript variable using a string that contains the name of the variable?
(4 answers)
How to use a string as a variable name in Javascript? [duplicate]
(3 answers)
parse a string as an object from data attribute [duplicate]
(1 answer)
Use dynamic variable names in JavaScript
(19 answers)
Closed 9 years ago.
How can I make the code that follows to work?
var x = 'name';
and then, to use the value inside x, as it was a variable, and set it, so that if i want it to be NAME, i'll have the result:
var name = 'NAME';
Is it possible ?
Not directly, no. But, you can assign to window, which assigns it as a globally accessible variable :
var name = 'abc';
window[name] = 'something';
alert(abc);
However, a much better solution is to use your own object to handle this:
var name = 'abc';
var my_object = {};
my_object[name] = 'something';
alert(my_object[name]);
I haven't seen the rest of your code, but a better way might be to use an object.
var data = {foo: "bar"};
var x = "foo";
data[x]; //=> bar
var y = "hello";
data[y] = "panda";
data["hello"]; //=> panda
I think this is a little cleaner and self-contained than the window approach