不使用临时变量互换两个变量的值

 
1.数组直取值法
  var a=1,b=2;
  b = [a,a=b][0];
  console.log(a);  //2
  console.log(b);  //1
 
2.异或法
  a=a^b;
  b=b^a;
  a=a^b;
 
3..加减法
  var a=1,b=2;
  a = a+b;
  b = a-b;
  a = a-b;
  console.log(a);  //2
  console.log(b);  //1
 
4.类型转数组
  var a=1,b=2;
  a = [a,b];
  b = a[0];
  a = a[1];
  console.log(a);//2
  console.log(b);//1
 
5.类型转对象,赋属性
  var a=1,b=2;
  a = {
  a:b,
  b:a,
  };
  b =a.b;
  a =a.a;     //注意位置,b = a.b 要用到a 而 a = a.a 不会用到b, 所以要先取b的值
  console.log(a);//2
  console.log(b);//1
 
6.一行代码 运算赋值
  var a=1,b=2;
  a = b +0*(b=a);
  console.log(a);
  console.log(b);
7.拼接数组分隔取值
  var a=1,b=2;
  a = a + "," +b; 
       b = a; 
       a = a.split(",")[1]; 
       b = b.split(",")[0]; 
  console.log(a);
  console.log(b);
 
8.如果为Sting类型的两个变量     可以用拼接 也可以运算
  var a="hp",b="js";
  a = b +((b=a)?"":""); 
  console.log(a);
  console.log(b);

 

 
posted @ 2016-04-23 02:54  没错high少是我  阅读(367)  评论(0编辑  收藏  举报