2017-09-11 62 views
-1

關鍵我很新的node.js,但我不認爲這應該發生:入門未定義存在

const snekfetch = require('snekfetch'); 
const auth = require('../auth.json'); 
const totext = require('html-to-text'); 

exports.run = async (bot, message, args) => { 
    const content = args.join(" "); 
    const tagged = args[0]; 

    snekfetch.get("http://api.stackexchange.com/2.2/search?pagesize=1&order=desc&sort=votes&tagged="+tagged+"&intitle="+content+"&site=stackoverflow&key=censored") 
    .then(r => console.log(r["body"]["items"]["accepted_answer_id"])); 
    /* 
    var text = htmlToText.fromString(bodyofsnek, { 
     wordwrap: 130 
    }); 
    */ 
} 

此打印出不確定的。 去掉[「accepted_answer_id」]給我這個對象:

[{"tags":["javascript","object","undefined"],"owner":{"reputation":60056,"user_id":797,"user_type":"registered","accept_rate":68,"profile_image":"https://www.gravatar.com/avatar/aef85130bf44caa9b4de0a3153e758f2?s=128&d=identicon&r=PG","display_name":"Matt Sheppard","link":"https://stackoverflow.com/users/797/matt-sheppard"},"is_answered":true,"view_count":857526,"protected_date":1335343521,"accepted_answer_id":416327,"answer_count":37,"score":2180,"last_activity_date":1504076618,"creation_date":1219735508,"last_edit_date":1447031189,"question_id":27509,"link":"https://stackoverflow.com/questions/27509/detecting-an-undefined-object-property","title":"Detecting an undefined object property"}] 

而且我可以在那裏看到accepted_answer_id以其爲416327. 那麼爲什麼返回undefined值?

+0

項是一個數組。你需要用索引值來引用它,而不是鍵名。 – user2263572

+0

@ user2263572謝謝你的工作。爲什麼不把它作爲答案 – Qwerty

回答

2

items是一個數組。你需要用索引值來引用它,而不是鍵名。

例如:

r["body"]["items"][0]