3 回答
TA贡献1848条经验 获得超2个赞
上述语句将始终执行,if因为您使用了=而不是==或===
let request; // the scope should be outside the blocks
if(textOption == "text") {
request = {
input: { text: mytextvariable },
}
} else {
request = {
input: { ssml: mytextvariable },
}
}
TA贡献1841条经验 获得超3个赞
您需要括号和双/三等号来对值进行匹配。
if (textOption === "text") {
一种简短的方法是采用带有检查和替代方案的条件运算符。
var textOption = 'text',
mytextvariable = 'foo',
request = {
input: textOption === "text"
? { text: mytextvariable }
: { ssml: mytextvariable }
};
console.log(request);
TA贡献1848条经验 获得超10个赞
var textOption = 'text',
mytextvariable = 'foo',
request = {
input: { [textOption]: mytextvariable }
};
这种方式属性名称基于textOption变量值。
如果您的变量可以有多个值(不仅是文本和 ssml),您可以改用表达式
request = {
input: { [textOption === 'text' ? 'text' : 'ssml']: mytextvariable }
};
添加回答
举报