2025年2月17日 星期一

初探 Nullish coalescing assignment (??=)

 初探 Nullish coalescing assignment  (??=)

前言

  在先前的 初探 Nullish coalescing operator (??) 介紹過 ?? ,這次來學習跟它很像的 ??=  ,在此把學習的過程做個紀錄。


內容

  範例如下

let obj = {
  a : 1234
};
//
obj.a ??= 5678;
console.log( obj.a );//1234
//
obj.b ??= 9999;
console.log( obj.b );//9999
//
obj.c ??= undefined;
console.log( obj.c );//undefined
//
obj.d ??= null;
console.log( obj.d );//null


??= 是有賦值的特性,並不是像 == 之類比較,賦值的邏輯是當左側是 null 或 undefiend 則給予賦值,範例第一例由於 a 已經有數值,所以賦值不會成功, b 由於本來就沒值,所以賦值成功,如果左側原本沒值,右側賦予 null 或 undefined 會成功嗎?從 c 與 d 的結果來看答案是肯定的!


參考資料

[ developer.mozilla.org ] Nullish coalescing assignment (??=)


相關文章與資料

初探 Nullish coalescing operator (??)

沒有留言:

張貼留言