How to resolve TypeError: Cannot convert undefined or null to object

后端 未结 9 1266
生来不讨喜
生来不讨喜 2020-11-28 05:44

I\'ve written a couple of functions that effectively replicate JSON.stringify(), converting a range of values into stringified versions. When I port my code over to JSBin an

9条回答
  •  鱼传尺愫
    2020-11-28 06:41

    This is very useful to avoid errors when accessing properties of null or undefined objects.

    null to undefined object

    const obj = null;
    const newObj = obj || undefined;
    // newObj = undefined
    

    undefined to empty object

    const obj; 
    const newObj = obj || {};
    // newObj = {}     
    // newObj.prop = undefined, but no error here
    

    null to empty object

    const obj = null;
    const newObj = obj || {};
    // newObj = {}  
    // newObj.prop = undefined, but no error here
    

提交回复
热议问题