[javascript] TypeError 해결 방법 : 정의되지 않은 또는 null을 개체로 변환 할 수 없습니다.

JSON.stringify ()를 효과적으로 복제하여 값 범위를 문자열 버전으로 변환하는 몇 가지 함수를 작성했습니다. 내 코드를 JSBin으로 이식하고 일부 샘플 값에서 실행하면 제대로 작동합니다. 그러나 이것을 테스트하도록 설계된 사양 주자 에서이 오류가 발생합니다.

내 코드 :

  // five lines of comments
  var stringify = function(obj) {
  if (typeof obj === 'function') { return undefined;}  // return undefined for function
  if (typeof obj === 'undefined') { return undefined;} // return undefined for undefined
  if (typeof obj === 'number') { return obj;} // number unchanged
  if (obj === 'null') { return null;} // null unchanged
  if (typeof obj === 'boolean') { return obj;} // boolean unchanged
  if (typeof obj === 'string') { return '\"' + obj + '\"';} // string gets escaped end-quotes
  if (Array.isArray(obj)) {
    return obj.map(function (e) {  // uses map() to create new array with stringified elements
        return stringify(e);
    });
  } else {
    var keys = Object.keys(obj);   // convert object's keys into an array
    var container = keys.map(function (k) {  // uses map() to create an array of key:(stringified)value pairs
        return k + ': ' + stringify(obj[k]);
    });
    return '{' + container.join(', ') + '}'; // returns assembled object with curly brackets
  }
};

var stringifyJSON = function(obj) {
    if (typeof stringify(obj) != 'undefined') {
        return "" + stringify(obj) + "";
    }
};

테스터로부터받은 오류 메시지는 다음과 같습니다.

TypeError: Cannot convert undefined or null to object
    at Function.keys (native)
    at stringify (stringifyJSON.js:18:22)
    at stringifyJSON (stringifyJSON.js:27:13)
    at stringifyJSONSpec.js:7:20
    at Array.forEach (native)
    at Context.<anonymous> (stringifyJSONSpec.js:5:26)
    at Test.Runnable.run (mocha.js:4039:32)
    at Runner.runTest (mocha.js:4404:10)
    at mocha.js:4450:12
    at next (mocha.js:4330:14)

예를 들어 stringifyJSON (null)과 함께 실패한 것 같습니다.



답변

일반적인 대답

이 오류는 Object 를 인수로 예상 하지만 undefined 또는 null을 대신 전달 하는 함수를 호출 할 때 발생합니다.

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

일반적으로 실수로 발생하므로 해결책은 코드를 확인하고 null / 정의되지 않은 조건을 수정 하여 함수가 적절한 Object 를 얻 거나 전혀 호출되지 않도록하는 것입니다.

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

문제의 코드에 대한 답변

if (obj === 'null') { return null;} // null unchanged 은 주어진 null경우 평가하지 않고 문자열이 주어진 경우에만 평가됩니다 "null". 따라서 실제 null값을 스크립트에 전달 하면 코드의 Object 부분에서 구문 분석됩니다. 그리고 언급 된 것을 Object.keys(null)던졌습니다 TypeError. 이 문제를 해결하려면 if(obj === null) {return null}null 주위에 qout없이-를 사용 하십시오.


답변

대상 개체가 비어 있지 않은지 확인하십시오 ( null또는 undefined).

아래와 같이 빈 객체로 대상 객체를 초기화 할 수 있습니다.

var destinationObj = {};

Object.assign(destinationObj, sourceObj);


답변

이는 null 또는 정의되지 않은 개체의 속성에 액세스 할 때 오류를 방지하는 데 매우 유용합니다.

정의되지 않은 개체에 null

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

빈 개체에 정의되지 않음

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

빈 개체에 null

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


답변

React Native 프로젝트에서 같은 문제를 해결했습니다. 이것을 사용하여 해결했습니다.

let data = snapshot.val();
if(data){
  let items = Object.values(data);
}
else{
  //return null
}


답변

제 경우에는 Chrome에 Lucid 확장 프로그램을 추가했지만 그 순간에는 문제를 인식하지 못했습니다. 약 하루 동안 문제를 해결하고 프로그램을 뒤집은 후 누군가 Lucid를 언급 한 게시물에서. 내가 한 일을 기억하고 Chrome에서 확장 프로그램을 제거하고 프로그램을 다시 실행했습니다. 문제는 사라졌습니다. 저는 React와 함께 일하고 있습니다. 이것이 도움이 될 것이라고 생각했습니다.


답변

바꾸다

if (typeof obj === 'undefined') { return undefined;} // return undefined for undefined
if (obj === 'null') { return null;} // null unchanged

if (obj === undefined) { return undefined;} // return undefined for undefined 
if (obj === null) { return null;} // null unchanged


답변

Laravel을 사용 하는 경우 내 문제는 내 Route의 이름에있었습니다. 대신 :

Route::put('/reason/update', 'REASONController@update');

나는 썼다 :

Route::put('/reason/update', 'RESONController@update');

컨트롤러 이름을 수정하면 코드가 작동했습니다!