簡體   English   中英

JavaScript簡寫if +簡寫賦值

[英]Javascript shorthand if + shorthand assignment

我想知道是否有一種方法可以將簡寫if / else與簡寫+ =合並

像這樣:

var value;
$.each(data.events, function(index, element) {
    var otherValue = element.value;
    value = value ? value + otherValue : '';
}

預防的東西

value += otherValue

從在值未定義時開始添加“未定義”開始。

長版本將是:

var value;
$.each(data.events, function(index, element) {
    var otherValue = element.value;
    if(value){
        value = value + otherValue;
    }

}

我希望這個問題不要太混亂:)

像這樣:

value = value && value + otherValue || value

另一種可能的方式是:

value && (value += otherValue)

就像value是真實的一樣,請評估下一個條件(value += otherValue)

盡管我不會走這些路,但我認為我們在編碼中需要考慮的一件事不僅是代碼的短短,還在於可讀性。

我還是喜歡

if(value)
    value += otherValue;

因為它更容易閱讀和查看您那里有病

編輯:

我發布的Geeze幾乎與您在下面示例中的內容完全相反。 我會在這里刪除我的問題,但已接受= /

您可以使用AND &&運算符:

console.log('foo' && 'hello'); // prints hello
console.log(null && 'hello'); // prints null
console.log(undefined && null); // prints undefined
console.log('foo' && null && 'bar'); // prints null


var value;
$.each(data.events, function(index, element) {
    // if value is undefined, null, or empty then it stays the same.
    // otherwise add append the element value
    value = (value && value + element.value);
}

盡管這並不比您的原始書更具可讀性

var value;
$.each(data.events, function(index, element) {
    // if value is undefined, null, or empty then it stays the same.
    // otherwise add append the element value
    if(value) value += otherValue;
}

我在下面留下了原始答案,我已經閱讀了您的問題,並看到了您的第一個代碼段並對此進行了回答。 但是您的第二個代碼片段做了一些不同的事情,我不確定現在的答案是什么...


您可以|| 運算符,它將返回表達式為true時看到的第一個未定義值(例如: !!val === true )或運算符序列中的最后一個值(假設您使用所有OR語句||

console.log(undefined || 'hello'); // prints hello
console.log('' || 'hello'); // prints hello
console.log(undefined || null); // prints null
console.log(undefined || '' || null); // prints null

因此,在您的情況下,使用您的工作時間更長的JavaScript代碼,我們可以將其簡化為以下內容

var value;
$.each(data.events, function(index, element) {
    value = (value && value+element.value);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM