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

后端 未结 9 1267
生来不讨喜
生来不讨喜 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:45

    Generic answer

    This error is caused when you call a function that expects an Object as its argument, but pass undefined or null instead, like for example

    Object.keys(null)
    Object.assign(window.UndefinedVariable, {})
    

    As that is usually by mistake, the solution is to check your code and fix the null/undefined condition so that the function either gets a proper Object, or does not get called at all.

    Object.keys({'key': 'value'})
    if (window.UndefinedVariable) {
        Object.assign(window.UndefinedVariable, {})
    }
    

    Answer specific to the code in question

    The line if (obj === 'null') { return null;} // null unchanged will not evaluate when given null, only if given the string "null". So if you pass the actual null value to your script, it will be parsed in the Object part of the code. And Object.keys(null) throws the TypeError mentioned. To fix it, use if(obj === null) {return null} - without the qoutes around null.

提交回复
热议问题