Javascript using variable as array name - javascript

I have several arrays in Javascripts, e.g.
a_array[0] = "abc";
b_array[0] = "bcd";
c_array[0] = "cde";
I have a function which takes the array name.
function perform(array_name){
array_name = eval(array_name);
alert(array_name[0]);
}
perform("a_array");
perform("b_array");
perform("c_array");
Currently, I use eval() to do what I want.
Is there any method not to use eval() here?

You can either pass the array itself:
function perform(array) {
alert(array[0]);
}
perform(a_array);
Or access it over this:
function perform(array_name) {
alert(this[array_name][0]);
}
perform('a_array');

Instead of picking an array by eval'ing its name, store your arrays in an object:
all_arrays = {a:['abc'], b:['bcd'], c:['cde']};
function perform(array_name) {
alert(all_arrays[array_name][0]);
}

Why can't you just pass the array?
function perform(array){
alert(array[0]);
}
perform(a_array);
perform(b_array);
perform(c_array);
Or am I misunderstanding the question...

why don't you pass your array as your function argument?
function perform(arr){
alert(arr[0]);
}

I believe any variables you create are actually properties of the window object (I'm assuming since you used alert that this is running in a web browser). You can do this:
alert(window[array_name][0])

Related

Return value in JavaScript using variable name

I made a function in my JavaScript, here is the scene:
Please note, the code below is just for my scenario, its not working.
getData('bill', 'userAge');
Function getData(u, variable) {
fetch(`url`).then(r=> { return response.json();})
.then(u => {
var userFullName = u.fullname;
var userAge = u.age;
var userGender = u.gender
return variable
});
}
when I execute the function getData('bill', 'userAge') which userAge is the variable name inside the function. And the function will return the value from variable name: userAge inside the function, so I dont have to write another code like, if(variable=='userAge') return userAge;
Is it possible ? Just asking, because I have ton of variables in my function, for now I'm still using if(variable=='userAge') return userAge
Well, answering directly your question: No, if you want to return exactly with the variable you are passing right now, you'll need to map each variable name to each return property.
BUT, if you pass directly and exactly the name of the property as variable parameter, then you can just use return u[variable]. For Example, instead of passing userFullName, you pass just fullname.
I'm not going to enter in the merit that your current example code being completely wrong because Function ... is not going to work since you should use function ..., but here below I made a functional example using a different approach to the fetch using await and async, you can see that it's returning the property I specified, which is "title".
async function getData(variable) {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1', {});
const u = await response.json();
return u[variable];
}
getData('title').then(a => {console.log(a)});
To check if my example returned the expected property from the object, you can access the link: JSON Example
One solution:
getData('bill', 'age');
function getData(u, variable) {
return fetch(`url`).then(r=> { return r.json();})
.then(u => {
return u[variable];
});
}
If you must use different names in your variable parameters than in your u properties, you can map them rather than use if/switch:
paramToVariable = {
userAge: 'age',
...
};
...
return u[paramToVariable[variable]];
Or you may use a function to map rather than an object.

Can a function receive an object as an argument in javascript?

var currentbutton = {};
function setPreset(obj) {
try{
if(obj.name===name && obj.value===value){
//log.error("preset array's OID at position ["+index+"] is"+presets[index].name +" and the value stored is "+presets[index].value);
currentbutton.name=obj.name;
currentbutton.value=obj.value;
log.error("currentbutton name= "+currentbutton.name+ "currentbutton value= " + currentbutton.value );
}
else
log.error("adklafjklajkl");
}
catch(ie){
log.error("couldn't set preset");
}
presets.forEach(function(obj));
I know there must be mistakes in this code that I wrote, first of all, I was told that the function need to receive an object as an argument, which I have no idea how to pass it to the function. I tried google, but I did not find any relevant information on whether a function can receive an object as an argument.
presets is an array which contains objects which has two properties (called "name" and "value")
basically, the array Presets goes through its enumerated list of variables with forEach, and compare if the argument obj's name and value are identical or not to any of the objects stored inside the array, if they are identical, set the currentbutton's name and value to the one inside the argument obj. Then we will have other functions which will operate on currentbutton that i don't have to worry about.
I know it's not really clear because I am not even sure if that's what is wanted of me.
You don't quite understand how forEach works. The forEach method takes a function as its argument:
[1,2,3].forEach(function(item) {
alert(item);
});
That function passed into forEach is given an argument itself. Here, I've named it item. The forEach method repeatedly invokes the function and supplies a successive member of the array as the first argument each time it is invoked.
Now, instead of passing in a literal function, I can use a variable to hold my function:
var alertStuff = function(item) {
alert(item);
}
Then, I use that function (referring to it by variable name) in forEach:
[1,2,3].forEach(alertStuff);
// is the same as...
[1,2,3].forEach(function(item) {
alert(item);
});
Thus, you want to use presets.forEach(setPreset);.
Define a function which accepts a paramter
function myNewFunc(obj){
alert(obj.myFirstProp);
}
Define an object which we are going to pass as an argument to the above function
var myObject = {
myFirstProp: "testing"
};
Call the function and pass the object as an argument
myNewFunc(myObject);
Your brackets were screwed up and you invoked forEach wrong.
var presets = [
{name:'a', value:1},
{name:'b', value:2},
{name:'c', value:3},
];
var currentbutton = {};
function setPreset(obj) {
try{
if(obj.name===name && obj.value===value){
//log.error("preset array's OID at position ["+index+"] is"+presets[index].name +" and the value stored is "+presets[index].value);
currentbutton.name=obj.name;
currentbutton.value=obj.value;
log.error("currentbutton name= "+currentbutton.name+ "currentbutton value= " + currentbutton.value );
} else { // syntax error, opening { of else block was missing
log.error("adklafjklajkl");
}
} // syntax error, closing } of try block was missing
catch(ie){
log.error("couldn't set preset");
}
} // syntax error, closing } of function was missiong
presets.forEach(setPreset);

TAFFYdb: Passing in options to a function

update: This code is bonkers. The root of the issue here is recreating the name of a variable by concating strings and assuming it would then magically turn into that variable.. I had a lot to learn. Also, a much better way to pass an ambiguous number of options into a function is to use JSON.
var availableTimes,
selected_unit,
selected_unit_number;
function createTimePicker(machineNumber){
availableTimes = machineNumber({booked:"no"}).select("time");
for (i=0;i<availableTimes.length;i++){
$('<option/>').val(availableTimes[i]).html(availableTimes[i]).appendTo('#signin_start_time');
}
}
$(function() {
$('body').on('click', '#cybex_arctrainer_button', function() {
selected_unit = "cybex_arctrainer";
});
$('body').on('change', '#signin_unit_number_selector', function () {
selected_unit_number = $("#signin_unit_number_selector option:selected").text();
unit_plus_number = selected_unit+selected_unit_number;
createTimePicker(unit_plus_number);
});
});
A few things: The database works. If I run createTimePicker(cybex_arctrainer1) it fills in the availableTimes variable just fine. The problem seems to be with combining selected_unit+selected_unit_number and passing them to createTimePicker.
Here:
machineNumber({booked:"no"})
machineNumber is a string, but you're trying to call it as if it is a function. You'll get the same error if you do something like
someVar = 'bob';
someVar();
You say that if you run
createTimePicker(cybex_arctrainer1);
but your code is not calling createTimePicker with the variable cybex_arctrainer1 as an argument, instead it's doing something more like:
createTimePicker('cybex_arctrainer1');

in jaydata: pass variables to filter, only global works

I have this function:
function db_borrarServer(idABorrar){
serversDB.servidores
.filter(function(elementoEncontrado) {
return elementoEncontrado.id_local == this.idABorrar;
})
.forEach(function(elementoEncontrado){
console.log('Starting to remove ' + elementoEncontrado.nombre);
serversDB.servidores.remove(elementoEncontrado);
serversDB.saveChanges();
});
}
does not work, but it does if I replace the variable "this.idABorrar" with a number, it does
return elementoEncontrado.id_local == 3;
or if I declare idABorrar as a global, works to.
I need to pass idABorrar as variable. How can I do this?
The EntitySet filter() function (as any other predicate functions) are not real closure blocks, rather an expression tree written as a function. To resolve variables in this scope you can only rely on the Global and the this which represents the param context. This follows HTML5 Array.filter syntax. To access closure variables you need to pass them via the param. Some examples
inside an event handler, the longest syntax is:
$('#myelement').click(function() {
var element = this;
context.set.filter(function(it) { return it.id_local == this.id; },
{ id: element.id});
});
you can also however omit the this to reference the params as of JayData 1.2 and also use string predicates
$('#myelement').click(function() {
var element = this;
context.set.filter("it.id_local == id", { id: element.id});
});
Note that in the string syntax the use of it to denote the lambda argument is mandatory.
In JayData 1.3 we will have an even simplex calling syntax
$('#myelement').click(function() {
var element = this;
context.set.filter("it.id_local", "==", element.id);
});
In the filter you should pass an object which is the this object, like this:
.filter(function(){},{idABorrar: foo})
foo can be const or any variable which is in scope.
The .filter() function takes an optional 2nd parameter which is assigned to this inside of the first parameter function.
So you can modify your code like so :
function db_borrarServer(idABorrar){
serversDB.servidores
.filter(function(elementoEncontrado) {
return elementoEncontrado.id_local == this;
}, idABorrar)
.forEach(function(elementoEncontrado){
console.log('Starting to remove ' + elementoEncontrado.nombre);
serversDB.servidores.remove(elementoEncontrado);
serversDB.saveChanges();
});
}
Let me know how you go - I'm very new to jaydata too and I've also been going a bit crazy trying to get my head into this paradigm.
But I came across your question trying to solve the same issue, and this is how I resolved it for me.

How to execute a JavaScript function when I send its name as string dynamically without parameters

I want execute JavaScript function which the name is coming as a string dynamically.
I don't need to pass any parameters while executing the function.
Please can any one guide me how to achieve this?
one simple way
eval("SomeFunction()");
or
var funcName = "SomeFunction";
var func == window[funcName];
func();
dangerous but you could use eval(method_name+"()")
are you talking about ´eval()´??
var foo = "alert('bar')";
eval(foo);
Hope this helps;
function a() {
console.log('yeah!');
}
var funcName = 'a'; // get function name
this[funcName]();
If the function is global, you should do window[funcName]() in browser.
Using eval is the worst way imaginable. Avoid that at all costs.
You can use window[functionname]() like this:
function myfunction() {
alert('test');
}
var functionname = 'myfunction';
window[functionname]();
This way you can optionally add arguments as well
Perhaps a safer way is to do something like this (pseudo code only here):
function executer(functionName)
{
if (functionName === "blammo")
{
blammo();
}
else if (functionName === "kapow")
{
kapow();
}
else // unrecognized function name
{
// do something.
}
You might use a switch statement for this (it seems like a better construct):
switch (functionName)
{
case "blammo":
blammo();
break;
case "kapow":
kapow();
break;
default:
// unrecognized function name.
}
You can optimize this by creating an array of function names, searching the array for the desired function name, then executing the value in the array.

Categories

Resources