我如何在这个模板字符串中制作条件?
How i can make conditionals in this template string?
现在我有这个对象:
const messages = {
required: field => `${field} needs to be filled!`,
}
打印我:
nome needs to be filled
我正在尝试在此模板字符串中设置一个条件,以根据条件更改字段的值。我试过类似的东西:
const messages = {
required: field => `
${field => {
if(field === 'nome') {
'name'
}
if(field === 'endereco') {
'address'
}
}} needs to be filled!
`,
}
但是当我打印我收到的消息时:
field => { if(field === 'nome') { return 'name' } } needs to be
filled!
我需要:
name needs to be filled
你搞得太复杂了
const field = "nome";
const messages = {
required: `${field === 'nome'?'name': field} needs to be filled!`
}
console.log(messages.required)
const messages1 = {
required: field => `${field === 'nome' ? 'name' : field} needs to be filled!`
}
console.log(messages1.required("nome"))
我相信你只能在模板文字中使用表达式,而不是语句(这就是你想要做的,使用 if
是一个语句)。您可以使用三元来创建表达式:
const messages = {
required: field => `${field === 'nome' ? 'name' : field} needs to be filled!`,
};
如果你有多个条件,那么你必须打破你的条件,并充实箭头函数一点:
const messages = {
required: field => {
let display;
if (field === 'nome') {
display = 'name';
} else if (field === 'other condition) {
display = 'other thing';
} else {
display = field;
}
return `${display} needs to be filled`;
},
};
const messages = {
required: field => `${field === "nome" ? "name" : field} needs to be filled!`,
}
在模板文字中你不能做多行表达式,比如函数,但你可以使用三元运算符。
现在我有这个对象:
const messages = {
required: field => `${field} needs to be filled!`,
}
打印我:
nome needs to be filled
我正在尝试在此模板字符串中设置一个条件,以根据条件更改字段的值。我试过类似的东西:
const messages = {
required: field => `
${field => {
if(field === 'nome') {
'name'
}
if(field === 'endereco') {
'address'
}
}} needs to be filled!
`,
}
但是当我打印我收到的消息时:
field => { if(field === 'nome') { return 'name' } } needs to be filled!
我需要:
name needs to be filled
你搞得太复杂了
const field = "nome";
const messages = {
required: `${field === 'nome'?'name': field} needs to be filled!`
}
console.log(messages.required)
const messages1 = {
required: field => `${field === 'nome' ? 'name' : field} needs to be filled!`
}
console.log(messages1.required("nome"))
我相信你只能在模板文字中使用表达式,而不是语句(这就是你想要做的,使用 if
是一个语句)。您可以使用三元来创建表达式:
const messages = {
required: field => `${field === 'nome' ? 'name' : field} needs to be filled!`,
};
如果你有多个条件,那么你必须打破你的条件,并充实箭头函数一点:
const messages = {
required: field => {
let display;
if (field === 'nome') {
display = 'name';
} else if (field === 'other condition) {
display = 'other thing';
} else {
display = field;
}
return `${display} needs to be filled`;
},
};
const messages = {
required: field => `${field === "nome" ? "name" : field} needs to be filled!`,
}
在模板文字中你不能做多行表达式,比如函数,但你可以使用三元运算符。