最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Swap the values of two variables in JavaScript - Stack Overflow

programmeradmin2浏览0评论

If I have a variable called foo set to the object: {example: '2', anotherExample: '1'} and another variable called anotherFoo set to 'orange' how would I swap the values of foo and anotherFoo? This would mean that foo = 'orange' and anotherFoo = {example: '2', anotherExample: '1'}.

If I have a variable called foo set to the object: {example: '2', anotherExample: '1'} and another variable called anotherFoo set to 'orange' how would I swap the values of foo and anotherFoo? This would mean that foo = 'orange' and anotherFoo = {example: '2', anotherExample: '1'}.

Share Improve this question asked Jun 25, 2017 at 19:49 urwoiurwoi 612 silver badges6 bronze badges 2
  • 2 Please show what you have tried that didn't work. – charlietfl Commented Jun 25, 2017 at 19:53
  • 3 Possible duplicate of How to swap two variables in JavaScript – Omri Luzon Commented Jun 25, 2017 at 20:03
Add a ment  | 

3 Answers 3

Reset to default 4

You can use an intermediate variable to hold the value of one.

var a = 1
var b = 2

var c = a
a = b
b = c

You can use a method shown in this link here but in my opinion is not very readable.

If you are using ES6+ try this:

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

Otherwise:

b = [a, a = b][0];
let foo = {
  example: '2',
  anotherExample: '1'
};

let anotherFoo = 'orange';

First, use a dummy variable to store the original value of one variable:

const dummy = anotherFoo;

Then, overwrite that variable with the original value of the second variable:

anotherFoo = Object.assign({}, foo);

Finally, overwrite the second variable with the original value of the first variable, which happens to be stored in the dummy variable:

foo = dummy;
发布评论

评论列表(0)

  1. 暂无评论