With ES6 destructuring, you can now swap without a temp variable. This applies to not only swapping variable values as in [a, b] = [b, a]
but more complex expressions involving properties of objects, like so: [obj.key1, obj.key2] = [obj.key2, obj.key1]
. To avoid more redundancy, you need to use a swap function:
function swap(obj, key1, key2) {
[obj[key1], obj[key2]] = [obj[key2], obj[key1]];
}
swap(obj, 'key1', 'key2');
The same idea applies with two objects and two keys:
function swap(obj1, key1, obj2, key2) {
[obj1[key1], obj2[key2]] = [obj2[key2], obj1[key1]];
}
swap(obj1, 'key1', obj2, 'key2');
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…