[英]Error “Object.keys called on non-object” caused by empty json output
I received an error Object.keys called on non-object
. 我收到
Object.keys called on non-object
的错误Object.keys called on non-object
。 The offending code is; 令人讨厌的代码是;
numberOfEmployees = Object.keys(employee_data).length;
employee_data
is a json object that gets assigned json output data from a web service. employee_data
是一个json对象,它从Web服务获取分配的json输出数据。 This error only happens when the json output is empty []
. 仅当json输出为空
[]
时,才会发生此错误。 If json output is not empty, there is no error. 如果json输出不为空,则没有错误。 What is wrong with the code?
代码有什么问题?
employee_data
becomes undefined
when the json output is empty []
. 当json输出为空
[]
时, employee_data
变为undefined
。
The error Object.keys called on non-object can only occured when you put non object into it. 仅当您将非对象放入对象时,才会发生对非对象调用的错误Object.keys。 See below in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
参见以下https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
return function(obj) {
if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
throw new TypeError('Object.keys called on non-object');
}
Did you test what is the value of employee_data when it is empty. 您是否测试了employee_data为空时的值是什么? It should work for [ ] .
它应该适用于[] 。
But if you have called JSON.stringify on it,than it won't work, See below. 但是,如果您在上面调用了JSON.stringify ,那么它将无法正常工作,请参见下文。
var emptyData = [];
if(typeof emptyData == 'object')
console.log(Object.keys(emptyData)); // it will print the keys,if there
var emptyData = [];
var emptyJSOn = JSON.stringify(emptyData);
if(typeof emptyJSOn == 'object')
console.log(emptyJson); // it won't print because ,it's not an object.
Now i suppose you are trying to pass, the emptyJson to Object.keys() method,which is why you are receiving this error. 现在,我想您正在尝试将emptyJson传递给Object.keys()方法,这就是为什么您收到此错误的原因。
For more information on this you can refer MDN docs. 有关此的更多信息,请参阅MDN文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.