swap() function for variables's values [duplicate]

北城余情 提交于 2019-12-19 12:23:08

问题


I am not able to achieve the desired result for this swap function below, where I want the values printed as 3,2

function swap(x,y){
 var t = x;
 x = y;
 y = t;
}

console.log(swap(2,3));

Any clue will be appreciated !


回答1:


Your function is swapping the values internally, but the function does not return a value.

The following method returns an array of values in reverse order of what was supplied.

function swap(x, y) {
    var t = x;
    x = y;
    y = t;
    return [x, y];
}

console.log(swap(2, 3));

However, you could easily do something like the following snippet, because - based on your supplied code - there seems to be no need to actually swap the values of the arguments.

function swap(x, y) {
    return [y, x];
}

console.log(swap(2, 3));



回答2:


If you don't actually need the values to swap:

function swap (x, y)
{
  return [y, x];
}

If you do need the values to swap, but you don't want to declare another variable:

function swap (x, y)
{
  x = x + y;
  y = x - y;
  x = x - y;
  return [x, y];
}


来源:https://stackoverflow.com/questions/40165189/swap-function-for-variabless-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!