我对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
});
*/
}
这打印出undefined。 删除[" 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 :(得分:2)
项目是一个数组。您需要使用索引值引用它,而不是键名。
例如:
r["body"]["items"][0]