create variable name function [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript dynamic variable name
I'm trying to create a function in javascript that has a name dependent on a variable.
For instance:
var myFuncName = 'somethingWicked';
function myFuncName(){console.log('wicked');};
somethingWicked(); // consoles 'wicked'
I can't seem to figure out a way to do it.... I tried to eval it, but then when I try and use the function at a later time it 'doesnt exist'.. or more exactly I get a ReferenceError that the function is undefined...
Any help would be appreciated.

You could assign your functions to an object and reference them like this:
var funcs = {};
var myFuncName = 'somethingWicked';
funcs[myFuncName] = function(){console.log('wicked');};
funcs.somethingWicked(); // consoles 'wicked'
Alternatively, you could keep them as globals, but you would still have to assign them through the window object:
var myFuncName = 'somethingWicked';
window[myFuncName] = function(){console.log('wicked');};
somethingWicked(); // consoles 'wicked'

var myFuncName = 'somethingWicked';
window[myFuncName] = function(){console.log('wicked');};
somethingWicked(); // consoles 'wicked'

Any time you have to create something that depends on a dynamic name for a variable you should be using a property of an object or an array member instead.
var myRelatedFunctions = {};
var myFuncName = 'somethingWicked';
myRelatedFunctions[myFuncName] = function (){console.log('wicked');};
myRelatedFunctions['somethingWicked']()

Related

Create JSON Array key dynamically in JavaScript [duplicate]

This question already has answers here:
Add a property to a JavaScript object using a variable as the name? [duplicate]
(14 answers)
Closed 3 years ago.
I'm Having a JSON that is getting creates in for-loop.
Here my main requirement is to create the Key from a predefined variable.
Here is the code that I'm using.
var rows =["Hello Trt", "Ho there", "I'm up"];
var name="Hello";
var jsonData = {};
var intentName=[];
var mainPersonel = {};
var intents = {};
intents.intentName = rows;
mainPersonel.intents=intents;
console.log(JSON.stringify(mainPersonel));
Looking into the other SO posts, I'm able to find on how can I replace intents variable, but here in my case, I want to replace intentName with name in the output.
Expected output is
{"intents":{"Hello":["Hello Trt","Ho there","I'm up"]}}
Please let me know on how can I achieve this.
Thanks
I think the below code satisfies your requirement.
var rows =["Hello Trt", "Ho there", "I'm up"];
var name="Hello";
var jsonData = {};
var intentName=[];
var mainPersonel = {};
var intents = {};
intents[name]= rows;
mainPersonel.intents=intents;
console.log(JSON.stringify(mainPersonel));
You can do like this:
intents[name]= rows;

Dynamically Select Variable [duplicate]

This question already has answers here:
Access value of JavaScript variable by name?
(7 answers)
Closed 5 years ago.
I have 2 variables like so
var variable_1 = "foo";
var variable_2 = "bar";
I use a function to grab the value of a checkbox input and for each checkbox which is checked, I want to load the particular variable which depends on value of checkbox.
$("input:checked").each(function() {
$(div).append('variable_'+$(this).val());
}
So I'd concatenate the text 'variable_' with the value of each checkbox.
Thanks!
You can use eval to get any variable values dynamically.
var variable_1 = "foo";
var variable_2 = "bar";
$("input:checked").each(function() {
$(div).append(eval('variable_'+$(this).val()));
}
Note: it's not the best solution because eval has some security issues as well.
Because calling a variable or function from a user input is dangerous, and particularly if you are only using two different variables, you would be better off using a simple if statement.
This one is a ternary if:
var variable_1 = "foo";
var variable_2 = "bar";
$("input:checked").each(function() {
var isChecked = $(this).is(':checked');
var append = (isChecked) ? variable_1 : variable_2;
$(div).append(append);
}
Alternatively you could use a switch statement for multiple values.
If the variables are globals then you can use
var y = window["variable_" + x];
to read or
window["variable_" + x] = y;
to write to them dynamically.
Better practice however is to use an object to store them instead of using separate variables...
var data = { variable_1: null,
variable_2: null };
...
y = data["variable_" + x];
Javascript can also use eval to access dynamically variables, amazingly enough even local variables
function foo(s) {
var x = 12;
return eval(s);
}
console.log(foo("x"));
and even more amazingly this allows the dynamic creation of new local variables...
var y = 42;
function foo(s) {
var x = 1;
eval(s);
return y; // may be global y or a local y defined by code in s
}
foo("x") // returns 42
foo("var y = 99") // returns 99 (but global y is not changed!)
but these uses of eval should be considered more a bug than a feature and are best avoided (they also makes the code basically impossible to optimize or understand so "just don't do it"™).
Create object with properties and access that properties via obj['prop'] notation, see code below:
var myObj = {'variable_1': 'foo', 'variable_2': 'bar'};
$("input:checked").each(function() {
var dynamicVariableName = 'variable_' + $(this).val()
var dynamicVarValue = myObj[dynamicVariableName];
$(div).append(dynamicVar);
}
If your variables lives under window it's better to create new global object which contains that variable rather than keeping that variables as globals.

Capturing variable names from a select

In the back end I have written some code that reads through a file and outputs to a list of JavaScript arrays for example, the page will see:
<script>
var peanuts = ["1","s","g","3","n"];
var cashewNuts = ["d","a","f","d","n"];
var PecanNuts = ["6","m","3","x","m"];
var BrazilNuts = ["j","n","7","v","s"];
var goingNuts = ["a","e","7","m","y"];
</script>
I then want to use an array based on the value of a somewhere else in that page.
So for example:
if($('select').val()===0){
alert(firstArray[1]);
}
My issue is that the variable names are decided on what is contained in the read file, I can't know this information. Is there a way to say for example
//collect the value from the select and assign it to a var
var varN = $('select').val();
//then collect another variable that has the variable name that
//equals the value of the 'varN'
I know this seems horrendous but unfortunately based on what I need to do, it is what I need to do :(
Yes. If for example your vars are in the global scope, you can do
var val = window[varN][0]; to get peanuts:1
If you do
var nuts = {
peanuts : ["1","s","g","3","n"],
cashewNuts : ["d","a","f","d","n"],
PecanNuts : ["6","m","3","x","m"],
BrazilNuts : ["j","n","7","v","s"],
goingNuts : ["a","e","7","m","y"]
}
then you can use
var val = nuts[varN][0];
If the variables are declared directly in <script>, you can use window[varN].

Javascript Element.onclick = functionName(as String)? [duplicate]

This question already has answers here:
Javascript - Variable in function name, possible?
(5 answers)
Closed 8 years ago.
I have function name in a var,
var i = 2; // iteration
var fname = 'myFunction' + i; // looks like myFunction2()
now i want to assign this function on element's event. i.e.
var elem = document.getElementById('e');
elem.onclick = fname;
It doesn't work. JS take function name as 'fname()' not the string inside it 'myFunction2()'
A little help would be appriciated,
Thanks in advance.
You can do this
window['myFunction' + i]
or create a array/object of functions.
var i = 2; // iteration
var fname = 'myFunction' + i; // looks like myFunction2()
var elem = document.getElementById('e');
elem.onclick = window[fname];
Check these answers: Javascript - Variable in function name, possible?
and Use JavaScript variable as function name?
What you attempt is to assign a string (variable) on an event.

Javascript Newb : How do I instantiate a var as "blah.1" and "blah.2"?

I currently have a block like this defining some vars
var slider_1 = document.querySelector('#slider_1');
var slider_2 = document.querySelector('#slider_2');
...
And func's that take ID's like this:
function updateFromInput(id){
if(id==1){
var x = input_1.value*1;
x = Math.round((x*ratio)-offset);
slider_1.x.baseVal.value = x/scale;
}else if(id==2){
var x = input_2.value*1;
x = Math.round((x*ratio)-offset);
slider_2.x.baseVal.value = x/scale;
}
};
I am trying to refactor a bit.
I'm thinking that if I could, instead, instantiate my vars with dots rather than underscores like
var slider.1 = document.querySelector('#slider_1');
var slider.2 = document.querySelector('#slider_2');
then I'd be able to better utilize the ID already getting passed into my func's and eliminate tons of duplication.
I was hoping to simplify my funcs with something like a single call for slider.id.x.baseVal.value = x/scale; rather than having to have that code in each of the IF/ELSE conditions.
When I try that though, I get an error saying " Uncaught SyntaxError: Unexpected number ".
How should this be done?
You can't use a plain numeric key in an object.
You can do this, though:
var slider = {}; // or = [], if array syntax is more appropriate
slider[1] = ...
slider[2] = ...
Furthermore, the syntax you suggested isn't allowed if the key is actually a variable rather than a literal token.
In your example slider.id actually refers to the object with literal key id, not whatever value the variable id happens to have.
You have to put the variable inside square brackets, i.e. slider[id], so your function would be written thus:
function updateFromInput(id){
var x = +input[id].value;
x = Math.round((x*ratio)-offset);
slider[id].x.baseVal.value = x/scale;
};
You can't. The . is an invalid character for a variable identifier.
You can use it in object properties though.
var sliders = {
"slider.1": document.querySelector('#slider_1'),
"slider.2": document.querySelector('#slider_2')
};
Then use the square bracket version of the member operator to access the property.
alert( sliders["slider.1"].id );

Categories

Resources