Replace a value if null or undefined in JavaScript

前端 未结 5 1411
刺人心
刺人心 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 01:55

    Logical nullish assignment, 2020+ solution

    A new operator is currently being added to the browsers, ??=. This is equivalent to value = value ?? defaultValue.

    ||= and &&= are also coming, links below.

    This checks if left side is undefined or null, short-circuiting if already defined. If not, the left side is assigned the right-side value.

    Basic Examples

    let a          // undefined
    let b = null
    let c = false
    
    a ??= true  // true
    b ??= true  // true
    c ??= true  // false
    
    // Equivalent to
    a = a ?? true
    

    Object/Array Examples

    let x = ["foo"]
    let y = { foo: "fizz" }
    
    x[0] ??= "bar"  // "foo"
    x[1] ??= "bar"  // "bar"
    
    y.foo ??= "buzz"  // "fizz"
    y.bar ??= "buzz"  // "buzz"
    
    x  // Array [ "foo", "bar" ]
    y  // Object { foo: "fizz", bar: "buzz" }
    

    Functional Example

    function config(options) {
        options.duration ??= 100
        options.speed ??= 25
        return options
    }
    
    config({ duration: 555 })   // { duration: 555, speed: 25 }
    config({})                  // { duration: 100, speed: 25 }
    config({ duration: null })  // { duration: 100, speed: 25 }
    

    ??= Browser Support Nov 2020 - 77%

    ??= Mozilla Documentation

    ||= Mozilla Documentation

    &&= Mozilla Documentation

提交回复
热议问题