首页 > 解决方案 > 使用变量查找值。JSON Alexa 技能

问题描述

嗨,我正在制作一个简单的 Alexa 技能,要求输入怪物名称并告诉你速度

我向用户询问怪物名称,然后用户的怪物名称存储在:handlerInput.requestEnvelope.request.intent.slots.name.value

我将它保存到变量怪物(下面的代码),所以它保存了用户给出的名称。

我还有一个名为typecharts的文件,那里有与怪物速度相关的数字。

类型图文件:

module.exports = {

    Werewolf: '60',
    Alien: "98",
    Herb: "10",
}; 

所以变量怪物(下面的代码)正确打印用户给出的名称,问题是这样的:

我尝试通过创建这个变量 const spe = (typecharts.monster)但它失败了,因为它不寻找用户所说的名称(保存在“monster”变量中),而是寻找“monster”,而不是里面的名称变量,¿如何让它查找存储在怪物中的文本?

代码修复:

    canHandle(handlerInput) {

        return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
            && Alexa.getIntentName(handlerInput.requestEnvelope) === 'CompareIntent';
                            },

    handle(handlerInput) {

        const monster = handlerInput.requestEnvelope.request.intent.slots.name.value
        const spe = (typecharts.monster) // <- i need to fix this to do what i need.

        return handlerInput.responseBuilder

            .speak("you said "+ monster +" with speed " + spe ) // <- alexa speech output
            .reprompt("tell me more")
            .getResponse();

    }

标签: jsonvariablesalexaalexa-skills-kitalexa-app

解决方案


使用括号语法来访问带有变量的对象键(否则,它将尝试找到一个名为“monster”的键,而您没有该键)。

handle(handlerInput) {

    const monster = handlerInput.requestEnvelope.request.intent.slots.name.value
    const spe = typecharts[monster]

    return handlerInput.responseBuilder

        .speak("you said "+ monster +" with speed " + spe ) // <- alexa speech output
        .reprompt("tell me more")
        .getResponse();

}

请记住处理没有找到怪物的情况,即

if (!spe) { ... } else { ... }

推荐阅读