I'm looking to swap two objects using a swap
function with just reference to them.
A typical use-case would be like this:
function swap(a, b) {
...
}
var a = [ { id: 1 }, { id: 2 } ]
swap(a[0], a[0])
console.log(a) // [ { id: 2 }, { id: 1 } ]
var one = { id: 1 }
var two = { id: 2 }
swap(one, two)
console.log(one) // Should be { id: 2 }
console.log(two) // Should be { id: 1 }
(Added some more use cases. swap
Should not be dependent on any array functionalities.)
Is this possible? I know that javascript's functions are copy-reference source. So essentially, swap(a, b)
's a
and b
is just a copy of a[0]
and a[1]
, so it seems like I can't swap them around without actually copying the fields of a
into the fields of b
and vice versa, which seems impractical.
edit: @timolawl pointed out ES6's destructuring, but it doesn't seem to work with this use case:
let a = [{ id: 1 }, { id: 2 }]
let one = a[0]
let two = a[1]
console.log(a[0])
console.log(a[1])
[one, two] = [two, one]
console.log(a[0])
console.log(a[1])