![](/img/trans.png)
[英]In JavaScript there an elegant way to merge two Objects and sum any common properties?
[英]Is there an elegant way to compare two objects for whether they exist in javascript?
我正在像這樣比較兩個對象:
if (obj1 !== null && obj2 !== null) {
// do thing 1
} else if (obj1 == null && obj2 == null) {
// also do thing 1
} else if (obj1 !== null) {
// return obj1
} else {
// return obj2
}
對於兩個對象(無論它們是否存在)提出的所有四個方案都包括四行,實在是太不明智了。 有沒有更清潔的方式來呈現這一點? 謝謝!
這是使用否定運算符將兩個obj引用都轉換為布爾值的捷徑,然后您就可以比較布爾值:
if (!obj1 == !obj2) {
// do thing 1
} else {
return obj1 || obj2;
}
說明:
!obj1 == !obj2
將評估為true
時,兩個都obj1
和obj2
是truthy或falsey,但如果一個是truty和其他falsey。 因此,如果兩個都為null,則結果將為true;如果兩個都不為null,則結果將為true;但是,如果只有一個為null,則它將為false。
return obj1 || obj2
return obj1 || obj2
將返回真實的值(例如非null)。
這將減少幾行時間:
if ((obj1 && obj2) || (!obj1 && !obj2)) {
// do thing 1
}
else
return (obj1 || obj2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.