Forgot password?
 Create new account
View 145|Reply 1

[js]交换变量

[Copy link]

3147

Threads

8497

Posts

610K

Credits

Credits
66183
QQ

Show all posts

hbghlyj Posted at 2022-3-8 05:58:08 |Read mode
  1. a=2100;b=12;b=b-a;a=a+b;b=a-b;
Copy the Code
这样就得到
  1. a
  2. 12
  3. b
  4. 2100
Copy the Code
变量被交换了.但是如果写成函数
  1. function exchange(a,b){b=b-a;a=a+b;b=a-b;}
Copy the Code
再调用:
  1. c=2100;d=12;exchange(c,d)
Copy the Code
这样得到
  1. c
  2. 2100
  3. d
  4. 12
Copy the Code
好像没有被交换?

3147

Threads

8497

Posts

610K

Credits

Credits
66183
QQ

Show all posts

 Author| hbghlyj Posted at 2022-3-8 06:00:43
  1. a=2100;b=12;[b,a]=[a,b];
  2. a
  3. 12
  4. b
  5. 2100
Copy the Code
这样写可以正常交换
  1. function exchange(a,b){[b,a]=[a,b]}
  2. c=2100;d=12;exchange(c,d);
  3. c
  4. 2100
  5. d
  6. 12
Copy the Code
这样写不会被交换....为什么呢

手机版Mobile version|Leisure Math Forum

2025-4-21 01:27 GMT+8

Powered by Discuz!

× Quick Reply To Top Return to the list