Replace a value if null or undefined in JavaScript

前端 未结 5 1403
刺人心
刺人心 2020-11-30 01:35

I have a requirement to apply the ?? C# operator to JavaScript and I don\'t know how. Consider this in C#:

int i?=null;
int j=i ?? 10;//j is now         


        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 02:10

    Here’s the JavaScript equivalent:

    var i = null;
    var j = i || 10; //j is now 10
    

    Note that the logical operator || does not return a boolean value but the first value that can be converted to true.

    Additionally use an array of objects instead of one single object:

    var options = {
        filters: [
            {
                name: 'firstName',
                value: 'abc'
            }
        ]
    };
    var filter  = options.filters[0] || '';  // is {name:'firstName', value:'abc'}
    var filter2 = options.filters[1] || '';  // is ''
    

    That can be accessed by index.

提交回复
热议问题