我已经编写了几个函数来有效地复制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)
发布于 2019-08-19 17:21:14
确保目标对象不为空( null
或undefined
)。
您可以使用空对象初始化目标对象,如下所示:
var destinationObj = {};
Object.assign(destinationObj, sourceObj);
发布于 2020-08-11 21:24:58
这对于避免访问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
发布于 2021-12-13 07:19:26
在将对象放到map上之前,添加"Object &&“是有效的。objexts && Object.keys(objexts )?.map((objext,idx) =>
https://stackoverflow.com/questions/29721205
复制相似问题