由空json输出引起的错误"在非对象上调用的Object.keys"

use*_*486 2 javascript arrays json javascript-objects

我收到了一个错误Object.keys called on non-object.违规代码是;

numberOfEmployees = Object.keys(employee_data).length;
Run Code Online (Sandbox Code Playgroud)

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

employee_dataundefined当json输出为空时变为[].

RE3*_*350 6

在非对象上调用的错误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');
      }
Run Code Online (Sandbox Code Playgroud)

你是否测试了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.
Run Code Online (Sandbox Code Playgroud)

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

有关此内容的更多信息,请参阅MDN文档.