最佳答案
我已经编写了几个有效复制 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)