簡體   English   中英

dailogflow中數組中的最大元素

[英]Max element in an array in dailogflow

我正在嘗試計算數組中的最大元素。 我嘗試了這段代碼,但它返回 [object Object] 在 dailogflow 中我是否缺少某些東西。

 function studentgroup(agent){ let games = [ { id: 1, name: 'Star Wars: Imperial Assault', votes: 3}, { id: 2, name: 'Game of Thrones: Second Edition', votes: 4 }, { id: 3, name: 'Merchans and Marauders', votes: 5 }, { id: 4, name: 'Eclipse', votes: 6 }, { id: 5, name: 'Fure of Dracula', votes: 2 } ]; let maxGame = games.reduce((max, game) => max.votes > game.votes? max: game); agent.add(`${maxGame}`); }

您可以通過遍歷數組來簡單地找到最大元素。

 let games = [ { id: 1, name: 'Star Wars: Imperial Assault', votes: 3}, { id: 2, name: 'Game of Thrones: Second Edition', votes: 4 }, { id: 3, name: 'Merchans and Marauders', votes: 5 }, { id: 4, name: 'Eclipse', votes: 6 }, { id: 5, name: 'Fure of Dracula', votes: 2 } ]; maxElement = -Infinity; element = null for (const game of games) { if (game.votes > maxElement) { maxElement = game.votes; element = game; } } console.log(element)

問題是maxGame是 object。 使用您的示例, object 將是

{ id: 4, name: 'Eclipse',  votes: 6 }

但是agent.add()期望發回一個字符串。 如您所見,object 的默認“字符串”形式是“[object Object]”。

您可能希望返回在顯示或朗讀時更有意義的內容,因此該行可能更有意義

agent.add(`The winner, with ${maxElement.votes} votes, is ${maxElement.name}.`)

舉個例子,它會說類似

獲得 6 票的獲勝者是 Eclipse。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM