对话框流中数组中的最大元素

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 是一个对象。使用您的示例,该对象将是

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

但是 agent.add() 期望发回一个字符串。如您所见,对象的默认 "string" 形式是“[object Object]”。

您可能想要 return 一些在显示或大声朗读时更有意义的内容,因此该行可能更有意义

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

举个例子,它会说类似

The winner, with 6 votes, is Eclipse.