Swap Parameter Function Infinite Variable Return Possibility | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 2

Swap Parameter Function Infinite Variable Return Possibility

Say we have a function: function swap(num1, num2) { num1 += num2; num2 = num1 - num2; num1 -= num2; return num1, num2; } Is it possible to do the following code: var a = 3; var b = 6; var c = 5; var d = 10; swap(a, b); //a = 6, b = 3 swap(c, d); //c = 10, d = 5 swap(a, d); //a = 5, d = 6 Basically, is it possible to swap AS MUCH AS WANTED of the global variables by calling the function like that? I don't want to say: function swap(num1, num2) { //all code before a = num1; b = num2; } Because that will only change those 2 vars (a and b). I want it to be able to swap as many variables as are called. (a, b, c, q, x, y, z etc) How do I make it possible?

21st Jun 2018, 7:07 PM
Andre Daniel
Andre Daniel - avatar
2 ответов
+ 2
I want to know how to change the values of global variables from inside a function.
21st Jun 2018, 8:04 PM
Andre Daniel
Andre Daniel - avatar
+ 1
Not sure about what the question is... Could it be one of those: (1) if the swap function always swap pairs, you can call the swap function as much as you want (2) I if you want to pass an unknown number of parameters to the swap function, you will have to pass them as an array or a kind of list, then perform your "multiple swap" algorithm. (look at the bubble sort algorithm as an example)
21st Jun 2018, 7:34 PM
ifl
ifl - avatar