Skip to content

[js] 第46天 写一个使两个整数进行交换的方法(不能使用临时变量) #175

Open
@haizhilin2013

Description

@haizhilin2013
Collaborator

第46天 写一个使两个整数进行交换的方法(不能使用临时变量)

Activity

xiangshuo1992

xiangshuo1992 commented on Jun 2, 2019

@xiangshuo1992
Contributor

利用运算符优先级和0*
b = a + 0 * (a = b);
利用执行顺序

a = a + b;
b = a - b;
a = a - b;

异或取值

a ^= b;
b ^= a;
a ^= b;
chwech

chwech commented on Jun 3, 2019

@chwech
let a = 1, b= 2
[a, b] = [b, a]
wenyejie

wenyejie commented on Jun 3, 2019

@wenyejie

利用运算符优先级和0*
b = a + 0 * (a = b);
利用执行顺序

a = a + b;
b = a - b;
a = a - b;

异或取值

a ^= b;
b ^= a;
a ^= b;

我去这种骚操作, 我只知道一个解构.

myprelude

myprelude commented on Jun 13, 2019

@myprelude
  • ES6
let [a,b] = [b,a]  
  • ES5
var a = 1,b = 2;
a = b+a;
b = a-b;
a = a-b;
chenliwen123

chenliwen123 commented on Jul 20, 2019

@chenliwen123
  • ES6
let [a,b] = [b,a]  
  • ES5
var a = 1,b = 2;
a = b+a;
b = a-b;
a = a-b;

ES 6 这个 优秀

seho-dev

seho-dev commented on Sep 15, 2019

@seho-dev

不能使用临时变量的是什么意思求解答

vincent-yan

vincent-yan commented on Sep 16, 2019

@vincent-yan
zxl-lxz

zxl-lxz commented on Mar 31, 2020

@zxl-lxz
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a, b); // => 2, 1
blueRoach

blueRoach commented on Jul 22, 2020

@blueRoach

let a = 1, b = 2
return [a, b] = [b, a]

Alex-Li2018

Alex-Li2018 commented on Aug 11, 2020

@Alex-Li2018
  1. 第一种
let b = 1
let c = 2
let tmp
tmp = b
b = c
c = tmp
  1. 第二种
let a = 1;
let b = 2;
[a, b] = [b, a];
smile-2008

smile-2008 commented on Nov 12, 2020

@smile-2008

利用运算符优先级和0*
b = a + 0 * (a = b);
利用执行顺序

a = a + b;
b = a - b;
a = a - b;

异或取值

a ^= b;
b ^= a;
a ^= b;
OldSixLi

OldSixLi commented on Feb 22, 2022

@OldSixLi

分享个新鲜的用法

let a = 0;
let b = 1;
a = [b, b = a][0];
console.log(a, b);
xiaoqiangz

xiaoqiangz commented on Jun 6, 2022

@xiaoqiangz

es6 解构
[a,b] = [b,a]

Sobrium

Sobrium commented on Sep 19, 2022

@Sobrium

ES6解构赋值 [a, b] = [b, a];
ES5 a = a + b;
b = a - b;
a = a - b;

panpanxuebing

panpanxuebing commented on Dec 11, 2024

@panpanxuebing
let x = 1;
let y = 2;

// 数组解构
[x, y] = [y, x]

// 运算符优先级
y = x + 0 * (x = y)

// 执行顺序
x = x + y
y = x - y
x = x - y

// 异或
x ^= y
y ^= x
x ^= y

console.log(x, y) // 2 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    jsJavaScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @smile-2008@wenyejie@haizhilin2013@vincent-yan@xiaoqiangz

        Issue actions

          [js] 第46天 写一个使两个整数进行交换的方法(不能使用临时变量) · Issue #175 · haizlin/fe-interview