有一种众所周知的方法可以交换2个数值变量而不使用带有简单算术运算的第3个变量。
Map
这里没有神秘感。但是我需要交换两个作为对象的变量,我不知道如何解决这个问题。
对象非常复杂,具有不同数据类型和方法的属性。以下是简化示例:
MySqlCommand cmd1 =
new MySqlCommand(
"INSERT INTO quotedetails (name, address, district, date, forto, refto, total) VALUES('" + txttoname.Text + "', '" + txttoaddress.Text.Replace("\r\n", "<br />").ToString() + "', '" + txtdistrict.Text + "' , '" + dateTimePicker1.Value.Date.ToString("yyyy-MM-dd") +"', '" + txtfor.Text + "', '" + txtref.Text + "', '" + txttotal.Text + "')", conn);
{
我目前正在使用第三个变量来执行交换,但是对象非常大,并且它正在弄乱变量交换值的动画。
答案 0 :(得分:1)
使用ES6数组解构。
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a);
console.log(b);
参考:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
答案 1 :(得分:0)
交换对象时使用第三个变量。在ES5中没有更简单的方法。
var first = {property: 'value'}
var second = {more: 'stuff'}
console.log('Before')
console.log(first)
console.log(second)
var temp = first
first = second
second = temp
console.log('After')
console.log(first)
console.log(second)
答案 2 :(得分:0)
var a=1,
b=2,
output=document.getElementById('output');
output.innerHTML="<p>Original: "+a+", "+b+"</p>";
b = [a, a = b][0];
output.innerHTML+="<p>Swapped: "+a+", "+b+"</p>";
<div id="output"></div>
答案 3 :(得分:0)
尝试ES6 Array Destructing assignment。
<强>样本强>
let a = {
label: "111111",
active: false,
doThatThang: function(val) {
//some code
}
};
let b = {
label: "222222",
active: false,
doThatThang: function(val) {
//some code
}
};
console.log("Before swap");
console.log(a);
console.log(b);
[a, b] = [b, a];
console.log("After swap");
console.log(a);
console.log(b);
&#13;
答案 4 :(得分:-4)
假设a = 3且b = 5。 然后
a = a+b (ie 8)
b= a-b (ie 8-5 = 3)
a= a-b (ie 8-3 = 5).
现在这些都是在不使用第三个变量的情况下交换的。