Replace a value if null or undefined in JavaScript

前端 未结 5 1386
刺人心
刺人心 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:14

    Destructuring solution

    Question content may have changed, so I'll try to answer thoroughly.

    Destructuring allows you to pull values out of anything with properties. You can also define default values when null/undefined and name aliases.

    const options = {
        filters : {
            firstName : "abc"
        } 
    }
    
    const {filters: {firstName = "John", lastName = "Smith"}} = options
    
    // firstName = "abc"
    // lastName = "Smith"
    

    NOTE: Capitalization matters

    If working with an array, here is how you do it.

    In this case, name is extracted from each object in the array, and given its own alias. Since the object might not exist = {} was also added.

    const options = {
        filters: [{
            name: "abc",
            value: "lots"
        }]
    }
    
    const {filters:[{name : filter1 = "John"} = {}, {name : filter2 = "Smith"} = {}]} = options
    
    // filter1 = "abc"
    // filter2 = "Smith"
    

    More Detailed Tutorial

    Browser Support 92% July 2020

提交回复
热议问题