gpt4 book ai didi

javascript - 未定义的逻辑出错

转载 作者:行者123 更新时间:2023-11-29 21:46:15 24 4
gpt4 key购买 nike

我正在使用 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);

});

}

我的错误是无法读取未定义的规范化文本

最佳答案

您正在尝试访问一个有时可能 undefined object ,即否定的。最好在尝试访问之前检查否定是否为 null。

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;
}

关于javascript - 未定义的逻辑出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31092949/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com