由空 json 输出导致的错误“在非对象上调用对象键”

Error "Object.keys called on non-object" caused by empty json output

本文关键字:对象 调用 输出 json 错误 由空      更新时间:2023-09-26

我收到错误Object.keys called on non-object。有问题的代码是;

numberOfEmployees = Object.keys(employee_data).length;

employee_data 是一个 JSON 对象,用于从 Web 服务获取分配的 JSON 输出数据。仅当 json 输出为空时,才会发生此错误 [] 。如果 json 输出不为空,则没有错误。代码有什么问题?

当 JSON 输出为空时,employee_data []变为undefined

只有在将非对象放入其中时,才会在非对象上调用错误 Object.keys 发生。见下文 https://developer.mozilla.org/en-US/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');
      }

您是否测试了employee_data为空时的值是多少。它应该适用于 [ ]。

但是如果你在上面调用了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.

现在我想你正在尝试传递,emptyJson到Object.keys()方法,这就是你收到此错误的原因。

有关这方面的更多信息,您可以参考 MDN 文档。