简体   繁体   English

dailogflow中数组中的最大元素

[英]Max element in an array in dailogflow

I am trying to calculate max element in an array.我正在尝试计算数组中的最大元素。 I tried this code but it is returning [object Object] Is there something i am missing while doing 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}`); }

You can simply find the maximum element by iterating over the array.您可以通过遍历数组来简单地找到最大元素。

 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)

The issue is that maxGame is an object.问题是maxGame是 object。 Using your example, that object will be使用您的示例, object 将是

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

But agent.add() is expecting to send back a string.但是agent.add()期望发回一个字符串。 The default "string" form of an object is "[object Object]", as you've seen.如您所见,object 的默认“字符串”形式是“[object Object]”。

You probably want to return something that makes more sense when displayed or read aloud, so it might make more sense for that line to be something like您可能希望返回在显示或朗读时更有意义的内容,因此该行可能更有意义

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

which, given the example, would say something like举个例子,它会说类似

The winner, with 6 votes, is Eclipse.获得 6 票的获胜者是 Eclipse。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM