未定义的逻辑出错了

时间:2015-06-27 19:59:13

标签: javascript ajax

我正在使用hp on demand API,它会返回一个对象,就像这个形式一样,用于正面查询。

var obj = {
  "positive": [
    {
      "sentiment": "love",
      "topic": null,
      "score": 0.8053406931054015,
      "original_text": "I love you",
      "original_length": 10,
      "normalized_text": "I love you",
      "normalized_length": 10
    }
  ],
  "negative": [],
  "aggregate": {
    "sentiment": "positive",
    "score": 0.8053406931054015
  }
}

对于否定查询,它会返回这样的对象

{
  "positive": [],
  "negative": [
    {
      "sentiment": "hate",
      "topic": null,
      "score": -0.8748623139495181,
      "original_text": "I hate you",
      "original_length": 10,
      "normalized_text": "I hate you",
      "normalized_length": 10
    }
  ],
  "aggregate": {
    "sentiment": "negative",
    "score": -0.8748623139495181
  }
}

我正在尝试将属性normalized_text分配给文本,但使用undefined似乎存在逻辑错误。这是我的代码

var arr = ["I hate you", "I love you", "I miss you"];

var emotions = [];

for(var i=0; i<arr.length; i++){

//console.log(arr[i]);
    $.ajax({

  url: "https://api.idolondemand.com/1/api/sync/analyzesentiment/v1?text="+arr[i]+"&apikey=e3b26b74-bla"

  })
  .done(function( data ) {
    var obj = data;
    //emotions.push(obj.aggregate.sentiment);
    var text;
    if(typeof obj.positive[0].normalized_text === "undefined"){
        text = obj.negative[0].normalized_text;
    }else{
    text = obj.positive[0].normalized_text;
    }

    console.log(text);   
    console.log(obj.aggregate.sentiment);

  });

}

我的错误是cannot read normalized_text of undefined

1 个答案:

答案 0 :(得分:2)

您正在尝试访问可能未定义的对象,即负数。在尝试访问之前,最好检查否定是否为空。

if (typeof obj.positive[0] !== "undefined") {
  text = obj.positive[0].normalized_text;
} else if (typeof obj.negative[0] !== "undefined") {
  text = obj.negative[0].normalized_text;
}