AWS Lambda中AMAZON.NUMBER类型插槽为何被拼接而非算术相加?
问题原因与解决方案
嘿,这个问题我太熟悉了!你遇到的是JavaScript里典型的类型隐式转换坑,核心原因很直白:
AMAZON.NUMBER类型的插槽值,从Alexa传递到AWS Lambda时,本质是字符串类型——哪怕用户说的是数字,比如"5",你拿到的也是字符串"5",而不是数字5。
当你在代码里直接把这个字符串和this.attributes['currentCount']相加时,JavaScript会默认把两者都当成字符串做拼接操作,而不是算术加法。比如如果currentCount是3,count是"2",结果就会是"32"而不是5。
修复方案
只需要把插槽值转换成数字类型再做运算就行,有两种常用方式:
- 使用
parseInt()(适合整数场景):
'CountSeveralTimes': function(){ // 把字符串类型的插槽值转成整数,第二个参数10是指定十进制,避免意外进制问题 var count = parseInt(this.event.request.intent.slots.count.value, 10); this.attributes['currentCount'] = this.attributes['currentCount'] + count; this.response.speak("Nice Job! You have now counted " + this.attributes['currentCount']+ " times."); }
- 使用
Number()(支持整数和小数):
'CountSeveralTimes': function(){ var count = Number(this.event.request.intent.slots.count.value); this.attributes['currentCount'] = this.attributes['currentCount'] + count; this.response.speak("Nice Job! You have now counted " + this.attributes['currentCount']+ " times."); }
额外注意点
还要确保this.attributes['currentCount']的初始值是数字类型,比如在会话启动时初始化:
'SessionStarted': function() { this.attributes['currentCount'] = 0; // 初始化为数字0,而不是字符串"0" }
如果初始值是字符串,哪怕是"0",相加时还是会触发拼接哦。
内容的提问来源于stack exchange,提问作者Ryan McCord
相关产品推荐
相关产品推荐

