@assistant/conversation中CollectionBrowse循环用法及动态条目实现问题
解决CollectionBrowse动态生成items的循环写法问题
问题出在你试图在数组字面量里直接插入for循环语句——JavaScript不允许这么做,数组字面量[]中只能包含表达式(比如对象、值、函数调用等),不能直接放置for这类流程控制语句,所以会导致解析错误。下面是几种可行的实现方案:
方案1:先创建数组,用for循环填充
这是最直观的写法,先初始化空数组,再通过循环把每个条目推进去:
app.handle('callApi', (conv) => { // 初始化空数组 const items = []; // 循环生成3个条目 for(let i = 1; i < 4; i++){ items.push({ title: `Item #${i}`, description: `Description of Item #${i}`, footer: `Footer of Item #${i}`, image: { url: 'https://developers.google.com/assistant/assistant_96.png', }, openUriAction: { url: 'https://www.example.com', }, }); } // 把生成好的数组传入CollectionBrowse conv.add(new CollectionBrowse({ items })); });
方案2:用Array.from生成数组(更简洁)
Array.from可以快速基于长度生成数组,同时通过回调函数处理每个元素:
app.handle('callApi', (conv) => { const items = Array.from({ length: 3 }, (_, index) => { const i = index + 1; // 从1开始计数 return { title: `Item #${i}`, description: `Description of Item #${i}`, footer: `Footer of Item #${i}`, image: { url: 'https://developers.google.com/assistant/assistant_96.png', }, openUriAction: { url: 'https://www.example.com', }, }; }); conv.add(new CollectionBrowse({ items })); });
方案3:用Array.fill + map组合
先创建指定长度的数组,再通过map转换每个元素:
app.handle('callApi', (conv) => { const items = new Array(3).fill(null).map((_, index) => { const i = index + 1; return { title: `Item #${i}`, description: `Description of Item #${i}`, footer: `Footer of Item #${i}`, image: { url: 'https://developers.google.com/assistant/assistant_96.png', }, openUriAction: { url: 'https://www.example.com', }, }; }); conv.add(new CollectionBrowse({ items })); });
这些方案都能实现你想要的动态生成效果,你可以根据自己的习惯选择其中一种。
内容的提问来源于stack exchange,提问作者박동석
相关产品推荐
相关产品推荐

