变量值的swap()函数 [英] swap() function for variables's values

查看:91
本文介绍了变量值的swap()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于下面的交换函数,我无法获得所需的结果,在这里我希望将值打印为3,2

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));

任何线索将不胜感激!

推荐答案

您的函数在内部交换值,但该函数不返回值.

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));

这篇关于变量值的swap()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆