1. 程式人生 > >不使用中間變數,交換int型的 a, b兩個變數的值

不使用中間變數,交換int型的 a, b兩個變數的值

(function(){
   var a = 10, b = 2;
   a = a + b;
   b = a - b;
   a = a - b;
   alert(a+" "+b);
})();

(function(){
   var a = 10,b=2;
   a = a^b;
   b = b^a;
   a = a ^b;
   alert(a+" "+b);
})();

(function(){
   var a =10,b =2 ;
   a=[a,b];
   b=a[0];
   a=a[1];
   alert(a+" "+b)
})();
//簡化一下:
(function(){
   var a =10,b =2 ;
   a=[b,b=a][0];
   alert(a+" "+b)
})();

(function(){
  var a = 10,b = 2;
  a = {a : b, b : a};
  b = a.b;
  a = a.a;
  alert(a+" "+b);
})();

(function(){
  var a = 10,b = 2;
  a=(function(){
    try {
      return b;
    }
    finally {
      b = a;
    } 
  })();
  alert(a+" "+b);
})();

(function(){
   var a = 10,b = 2;
   eval("a="+b+";b="+a);
   alert(a+" "+b);
})();

(function(){
   var a =10,b =2 ;
   a = b+(b = a)*0;
   alert(a+" "+b)
})();