【问题标题】:Fetching a value from a result?从结果中获取值?
【发布时间】:2020-01-30 06:42:22
【问题描述】:

所以我从 chuck norris api 获取值。当给定一个值时,例如使用来自 api 的 random 事件时,我能够获取和呈现值。我的问题是,当列表中显示多个值时,如何呈现给我的值?

let topic = args.join(" "); //defines topic set as varliable to use in query search

fetch(`https://api.chucknorris.io/jokes/search?query=${topic}`).then(result => result.json());
const { sub } = await fetch(`https://api.chucknorris.io/jokes/search?query=${topic}`).then(result => result.json());

if(topic !== " ") { return message.channel.send(sub)};

【问题讨论】:

  • 如果有多个 args,您是在问如何进行多个 API 调用?
  • 是的。如果我得到一个有 5 个值可供选择的结果列表。我想随机选择并显示它选择的值?现在我开始认为我没有任何意义哈哈

标签: node.js api botframework discord discord.js


【解决方案1】:

听起来您在问如何从数组中随机选择一项。 Math.random 为您提供 0 到 1 之间的随机数。如何将其转换为 Array 中的随机索引?先乘以数组的大小,然后用Math.floor 向下取整:

const response = await fetch(`https://api.chucknorris.io/jokes/search?query=${topic}`);
const jokes = await response.json();
const randomIndex = Math.floor(Math.random() * jokes.length);
const randomJoke = jokes[randomIndex];
return message.channel.send(randomJoke)

【讨论】:

  • 啊,谢谢。我从来没有想过我需要使用 Math.random,但我现在想要一个随机输出更有意义。
【解决方案2】:

从项目数组中选择随机值的最简单方法是执行以下操作:

const randomItem = allItems[Math.floor(Math.random() * allItems.length)];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-09
    • 2015-09-09
    • 2015-04-23
    • 2011-11-15
    • 2012-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多