我编写了几个有效复制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)
vep*_*oza 85
通用答案
当您调用一个期望将Object作为其参数的函数时,会导致此错误,但会传递undefined或null,例如
Object.keys(null)
Object.assign(window.UndefinedVariable, {})
因为这通常是错误的,所以解决方案是检查代码并修复null/undefined条件,以便函数获得正确的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}- 不要将qoutes置于null之外.
KAR*_*N.A 32
确保该对象不为空( null 或 undefined )。
错误:
let obj
Object.keys(obj)
解决方案:
Object.keys(obj || {})
确保目标对象不为空(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
小智 5
Object &&在将对象放到地图上之前添加工作。
objexts && Object.keys(objexts)?.map((objext, idx) =>