我正在浏览谷歌助手的NodeJS教程/谷歌https://codelabs.developers.google.com/codelabs/actions-1/#5上的操作,代码看起来像这样:
app.intent('Location', (conv, {geo-city}) => {
const luckyNumber = geo-city.length;
// Respond with the user's lucky number and end the conversation.
conv.close('Your lucky number is ' + luckyNumber);
});
无论是Dialogflow中的linter还是我的集成开发环境中的linter都对{geo-city}
不满意,但我找不到解决它的方法。我试过引号,反引号等,但没有乐趣。我不能更改变量名,因为它是一个Google AI系统实体(https://cloud.google.com/dialogflow-enterprise/docs/reference/system-entities)。
请问正确的处理方法是什么?
发布于 2019-06-06 04:39:05
您可以在Dialogflow参数列表中更改名称。虽然它使用基于实体类型的默认类型,但您可以将其更改为您想要的任何内容。
例如,给定以下训练短语,其中它选择了训练短语中的城市名称,为其分配了@sys.geo-city
类型,并为其提供了默认名称geo-city
您可以单击参数名称,对其进行编辑,然后将其更改为` `city。
因此,您的代码只使用city
作为参数名。
app.intent('Location', (conv, {city}) => {
const luckyNumber = city.length;
// Respond with the user's lucky number and end the conversation.
conv.close('Your lucky number is ' + luckyNumber);
});
如果你真的想把它命名为"geo-city",你仍然可以使用它作为参数名。函数的第二个参数只是一个依赖于Dialogflow参数名称的对象,他们正在使用一些JavaScript语法糖来解构它。但你没必要这么做。您可以使用类似这样的代码
app.intent('Location', (conv, params) => {
const luckyNumber = params['geo-city'].length;
// Respond with the user's lucky number and end the conversation.
conv.close('Your lucky number is ' + luckyNumber);
});
发布于 2019-06-06 04:33:43
这是对象析构语法。当你这样做时,例如:
const func = ({ foo }) => console.log('foo is', foo);
...您告诉JavaScript:func
将接受一个对象作为参数,但我只对名为foo
的对象的属性感兴趣,因此请将foo
属性的值放入名为foo
的变量中,并忽略其余的。
然而,尽管geo-city
在JavaScript中是一个有效的属性名,但它不是一个有效的变量名(否则将无法判断它是否是一个变量,或者您试图从geo
中减去city
)。解决这个问题的一种方法是将对象作为参数:
const func = (obj) => console.log('foo is', obj.foo);
...or,应用于您的代码:
app.intent('Location', (conv, obj) => {
const luckyNumber = obj['geo-city'].length;
// ...
});
但是解构是很好的,我们有另一种方法来让它工作。在解构对象时,可以为变量提供另一个名称:
const func = ({ foo: valueOfFoo }) => console.log('foo is', valueOfFoo);
即使是像geo-city
这样的属性也可以使用,但您必须将其放在引号中,如下所示:
app.intent('Location', (conv, {'geo-city': geoCity}) => {
const luckyNumber = geoCity.length;
// ...
});
https://stackoverflow.com/questions/56467409
复制相似问题