Javascript 如何解决 TypeError:无法将 undefined 或 null 转换为对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29721205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to resolve TypeError: Cannot convert undefined or null to object
提问by zahabba
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 and run it on some sample values, it functions just fine. But I'm getting this error in a spec runner designed to test this.
我编写了几个有效复制 JSON.stringify() 的函数,将一系列值转换为字符串化版本。当我将代码移植到 JSBin 并在一些示例值上运行它时,它运行得很好。但是我在一个旨在测试这个的规范运行器中遇到了这个错误。
My code:
我的代码:
// 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) + "";
}
};
The error message I'm getting from the tester is:
我从测试人员那里得到的错误消息是:
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)
It seems to fail with: stringifyJSON(null) for example
它似乎失败了:例如 stringifyJSON(null)
回答by veproza
Generic answer
通用答案
This error is caused when you call a function that expects an Objectas its argument, but pass undefinedor nullinstead, like for example
当您调用一个期望Object作为其参数的函数,但传递undefined或null 时,会导致此错误,例如
Object.keys(null)
Object.assign(window.UndefinedVariable, {})
As that is usually by mistake, the solution is to check your code and fix the null/undefinedcondition so that the function either gets a proper Object, or does not get called at all.
由于这通常是错误的,解决方案是检查您的代码并修复null/undefined条件,以便函数要么获得正确的Object,要么根本不被调用。
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 unchangedwill not
evaluate when given null, only if given the string "null". So if you pass the actual nullvalue to your script, it will be parsed in the Object part of the code. And Object.keys(null)throws the TypeErrormentioned. To fix it, use if(obj === null) {return null}- without the qoutes around null.
该行if (obj === 'null') { return null;} // null unchanged不会在给定时评估null,只有在给定字符串时才会评估"null"。因此,如果您将实际null值传递给脚本,它将在代码的对象部分进行解析。并Object.keys(null)抛出TypeError提到的。要修复它,请使用if(obj === null) {return null}- 没有围绕 null 的 qoutes。
回答by Yuvraj Patil
Make sure that destination object is not empty ( nullor undefined).
确保目标对象不为空(null或undefined)。
You can initialize destination object with empty object like below:
您可以使用空对象初始化目标对象,如下所示:
var destinationObj = {};
Object.assign(destinationObj, sourceObj);
回答by ziggybaba
I solved the same problem in a React Native project. I solved it using this.
我在 React Native 项目中解决了同样的问题。我用这个解决了它。
let data = snapshot.val();
if(data){
let items = Object.values(data);
}
else{
//return null
}
回答by Gev
Replace
if (typeof obj === 'undefined') { return undefined;} // return undefined for undefined
if (obj === 'null') { return null;} // null unchanged
代替
if (typeof obj === 'undefined') { return undefined;} // return undefined for undefined
if (obj === 'null') { return null;} // null unchanged
with
和
if (obj === undefined) { return undefined;} // return undefined for undefined
if (obj === null) { return null;} // null unchanged
回答by Behzad Akbari
In my case, I added Lucid extension to Chrome and didn't notice the problem at that moment. After about a day of working on the problem and turning the program upside down, in a post someone had mentioned Lucid. I remembered what I had done and removed the extension from Chrome and ran the program again. The problem was gone. I am working with React. I thought this might help.
就我而言,我在 Chrome 中添加了 Lucid 扩展程序,但当时没有注意到问题。经过大约一天的工作解决这个问题并将程序颠倒过来,在一篇文章中有人提到了 Lucid。我记得我做了什么,并从 Chrome 中删除了扩展程序,然后再次运行该程序。问题消失了。我正在使用 React。我认为这可能会有所帮助。
回答by Ivan Fernandez
I have the same problem with a element in a webform. So what I did to fix it was validate. if(Object === 'null') do something
我对网络表单中的元素有同样的问题。所以我为修复它所做的就是验证。if(Object === 'null') 做某事

