Home > Software engineering >  How to receive and maintain values in functions (javascript)
How to receive and maintain values in functions (javascript)

Time:11-19

Lets say I have this

anArray.filter(something)
//later
something(argumentno2)    

function something(argument1, argument2) {
    
    //do something with argument 1
    //do something with argument 2
    }

TDLR: Need to do work on the result of argument1 using argument2

My issue is that I don't receive the arguments in order, and my software seems to bug out as a result, argument 2 specially seems to return a number instead of its value, and most of the times returns nothing when its value is that of a string, I am not receiving the functions in order in my code, is there anyway to assign argument1 with the first slot and argument2 with the second, or at least a way to work around the problem, I hope this clarifies it somewhat, I am not too familiar with javascript terms, please ask questions if you need further elaboration.

CodePudding user response:

an update, I had a bug where it was reading from both a global variable and the passed variable, it works where either you pass or use a global variable, just not both, hence why I got undefined errors. the following is just a solution using the global variable, but I currently simply deleted the one I was using and pass it normally.

I have finally managed to find a solution, albeit it does not solve the original question ( solved ), I solved it by simply not passing two arguments to my function and instead pass just 1 and set the other as a global variable, this I am told is not an elegant solution, there are two ways to do this you can either declare your global variable outside all your functions but this does not work for me I assume because argumentno2 comes as an argument to another function entirely from a seperate script so I used this command to make it global

anArray.filter(something)                  //passes an array to function something, the array is recieved as argument1 one by one
//later
global.usethis_argumentno2 = argumentno2   //makes usethis_argumentno2 a global and sets its value to argumentno2

function something(argument1){             //recieves anArray as argument1
//do something with argument1
//do something with usethis_argumentno2 as its now a global
}

answer sourced from here

  • Related