I want to merge a argument of a function with a variable
But i don't know how to do that.
firstDates = [];
function myFunction(partOne) {
partOne + Dates.push(someOtherVar);
}
myFunction(first);
I know that this not works, but what would be the right way?
why not something like this?
var dates = {};
function myFunction(partOne) {
dates[partOne] = []; // dates["first"] = []
dates[partOne].push(someOtherVar); // dates["first"].push(someOtherVar)
}
myFunction("first");
Otherwise what you are trying to accomplish is an eval type of set up. This is generally a very bad idea. Don't use dynamically named variables.
Related
I have been told my function:
for (const key of Object.keys(temp)) {
this.sessionData.push(temp[key]);
}
Must now use a .map instead,
I have tried this below:
Object.keys(temp).map(function(key) {
this.sessionData[key];
})
But 1 I don't know if it's actually accurate, and also, it cant access the data outside of the scope of the function it is in, here is the whole function below:
public sessionData;
sessionDates(sessionsData) {
const temp = {};
this.sessionData = [];
sessionsData.forEach(session => {
const date = moment(session.startDatetime).format('DDMMYYYY');
if (temp[date]) {
temp[date].push(session);
} else {
temp[date] = [session];
}
});
Object.keys(temp).map(function(key) {
this.sessionData[key];
})
TRYING TO USE THIS BELOW... session data is undefined, it can't access out of the scope?
Object.keys(temp).map(function(key) {
this.sessionData[key];
})
But this works..
for (const key of Object.keys(temp)) {
this.sessionData.push(temp[key]);
}
So this new .map method can't access anything out of its scope.. sigh!
If anybody can help that would be amazing! Thanks!
In Javascript all functions can access variables from outside (called "higher scope") - it's one of the strengths of the language and is called "capture".
The reason your code is failing is because it's using this.sessionData inside a function declaration, which cases problems because this in javascript is... somewhat complex. But you don't need it!
You also need to make sure you return the value you want to output. Here's how I would write it:
this.sessionData = Object.keys(temp).map(key => temp[key]);
I'm trying to come up with something in this format:
"hours":{
"<default>":{
"mon_open_close":[...],
"tue_open_close":[...],
"wed_open_close":[...],
"thu_open_close":[...],
"fri_open_close":[...],
"sat_open_close":[...],
"sun_open_close":[...],
}
}
I have a bunch of variables defined like this (one for each day of the week):
var wed_open_close_hours = [operationTime[2].timeFrom+'-'+operationTime[2].timeTill];
That yields something like: [10:00-16:00]
And then have this array:
$all_hours_text = ['mon_open_close', 'tues_open_close' ,'wed_open_close' , 'thu_open_close' , 'fri_open_close' , 'sat_open_close' ,'sun_open_close'];
The issue I have is how to roll it all together and create this one single object. Can someone point me in the right direction?
So if you set
var wed_open_close_hours = [operationTime[2].timeFrom+'-'+operationTime[2].timeTill];
in a global scope, it will also be available as
window.wed_open_close_hours;
Otherwise it's available if you did something like eval("wed_open_close_hours");
So you could do
all_hours_text.map(function(varname) {
if(window[varname+"_hours"]) {
result["hours"]["<default>"][varname] = window[varname+"_hours"];
}
})
or
all_hours_text.map(function(varname) {
result["hours"]["<default>"][varname] = eval(varname+"_hours");
})
However, neither setting variables at the global scope nor using eval is recommended practice. You really should consider factoring the code to something like:
var output = {}
output.hours = {}
output.hours["<default>"] = {}
.,..
output.hours["<default>"].wed_open_close = [operationTime[2].timeFrom+'-'+operationTime[2].timeTill];
I have a function that create and store an array for all the p elements:
function dummyArray(){
var $dummy= $('p');
var dummy= [];
i = 0;
$dummy.each(function()
{
dummy[i++] =$(this).html();
});
return dummy;
}
Now, in order to reuse the array in another function, I can use dummyArray() and dummyArray()[0] to access the individual data.
function initAll(){
//dummyArray();
//dummyArray()[0];
}
However I want to store it inside a variable like below but it gives me error.
function initAll(){
var allArray = dummyArray();//error
}
Is there a way to store it inside a variable or is there a better way of doing this?
After cleaning up my code I noticed that using var allArray = dummyArray(); does work, the error was generated from something else. cheers~
Edited:
The error I found out was the function name cannot be the same as the new variable name declared even though the () aren't there.
var dummyArray = dummyArray();//error
var allArray = dummyArray();//works
This is some JS code
var methodArr = ['firstFunc','secondFunc','thirdFunc'];
for(var i in methodArr)
{
window[methodName] = function()
{
console.log(methodName);
}
}
My problem is that how to get the name of a function in JS.
In JS, use this.callee.name.toString() can get the function name. But in this situation, it is a null value. How can i get the 'funName' string?
Sorry, I didn't make it clear.
I want to create functions in a for loop, all these functions has almost the same implementation which need its name. But others can call these functions use different name.I want to know what methodName function is called.
it seems a scope problem.
Try this:
var methodArr = ['firstFunc','secondFunc','thirdFunc'];
for(var i in methodArr) {
var methodName = methodArr[i]; // <---- this line missed in your code?
window[methodName] = (function(methodName) {
return function() {
console.log(methodName);
}
})(methodName);
}
window['secondFunc'](); // output: secondFunc
I'm working on a code where I must pass a different function to some objects.
In this case, I'm trying to pass a different function for the onchange event. So currently what I got is something like this this:
var ArrayList; //Contains some data to use with ObjectArray format { n: data }
var ObjectArray; //Contains several objects format Array[n] = Object;
for(var key in ArrayList){
var doFunction = function() {
Object[key].doSomething(ArrayList[key]);
}
Object[key].onchange = doFunction;
}
The problem here I believe is that I'm afraid it will execute the code as it is declared and not with the values of the actual variables.
Is there a way to pass the function with the values as it executes? or will the variables get parsed the way its written?
It's the classic function in a loop problem. You need to understand how closures work.
Read the "Example 3" part of this answer carefully. The whole How do JavaScript closures work? question, too.
Another example that might help understand intuitively:
var key = 5;
var onchange = function () {
console.log(key);
};
onchange(); // 5
key = 10; // the loop reassigns the key on each iteration
onchange(); // 10
This is how it should be done:
var ArrayList; //Contains some data to use with ObjectArray format { n: data }
var ObjectArray; //Contains several objects format Array[n] = Object;
for(var key in ArrayList)
{
(function(key)
{
var doFunction = function()
{
Object[key].doSomething(ArrayList[key]);
}
Object[key].onchange = doFunction;
}(key))
}