简单的交换程序不工作javascript [重复]

时间:2023-02-09 16:51:38

This question already has an answer here:

这个问题在这里已有答案:

I've made the following swap function:

我做了以下交换功能:

function swap(a,b)
{
    var c=b;
    b=a;
    a=c;
}

It is supposed to swap 2 numbers. I have the follwing code:

它应该交换2个数字。我有以下代码:

var x=5;
var y=10;
swap(x,y);

The problem is that when I output the vaues of these variables after swap I still get 5 for x and 10 for y. Any ideas?

问题是,当我在交换后输出这些变量的值时,我仍然得到5为x,10为y。有任何想法吗?

1 个解决方案

#1


0  

Since the parameters are passed by value you cannot write a function that replaces the following:

由于参数是按值传递的,因此您无法编写替换以下内容的函数:

var a, b;
var temp = a;
a = b;
b = temp;

You can also use a one-liner:

你也可以使用单行:

b = [a, a = b][0];

#1


0  

Since the parameters are passed by value you cannot write a function that replaces the following:

由于参数是按值传递的,因此您无法编写替换以下内容的函数:

var a, b;
var temp = a;
a = b;
b = temp;

You can also use a one-liner:

你也可以使用单行:

b = [a, a = b][0];