gpt4 book ai didi

javascript - 我如何在此模板字符串中创建条件?

转载 作者:太空宇宙 更新时间:2023-11-04 03:12:56 26 4
gpt4 key购买 nike

现在我有这个对象:

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"))

关于javascript - 我如何在此模板字符串中创建条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60326316/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com