Javascript 如何基于布尔值在JS中的单词之间自动插入逗号或符号?

Javascript 如何基于布尔值在JS中的单词之间自动插入逗号或符号?,javascript,ecmascript-6,Javascript,Ecmascript 6,我知道这可以通过使用几个if…else语句来实现,但这真的很蹩脚。是否有其他方法实现此目标?您可以执行以下操作: const confirmations1={数量:假,总价:真,单价:真}; 常量确认2={数量:真,总价:真,单价:真}; const getFormatted句子=obj=>Object .钥匙(obj) .filter(k=>obj[k]) .map(k=>k .分割 .map(w=>w.charAt(0).toUpperCase()+w.slice(1)) .加入(“”)

我知道这可以通过使用几个
if…else
语句来实现,但这真的很蹩脚。是否有其他方法实现此目标?

您可以执行以下操作:

const confirmations1={数量:假,总价:真,单价:真};
常量确认2={数量:真,总价:真,单价:真};
const getFormatted句子=obj=>Object
.钥匙(obj)
.filter(k=>obj[k])
.map(k=>k
.分割
.map(w=>w.charAt(0).toUpperCase()+w.slice(1))
.加入(“”)
)
.join(“,”)
.替换(/,(?!*,)/gmi,,&');
日志(GetFormattedSequence(确认1));

日志(GetFormattedSequence(确认2))您可以使用另一个对象作为措辞,然后通过将最后两个单词替换为“与”,并将所有单词替换为“逗号”来创建一个漂亮的字符串

函数getString(确认){
常数
nice=a=>a.concat(a.splice(-2,2).join(“&”).join(“,”),
文字={数量:数量,总价:总价,单价:单价};
返回nice(对象)
.条目(确认)
.filter(([,v])=>v)
.map(([w])=>单词[w])
);
}
log(getString({数量:false,总价:true,单价:true});
log(getString({quantity:true,total_price:true,unit_price:true}));

log(getString({数量:false,总价:true,单价:false})这应该可以完成以下工作:

const confirmations = {
    quantity: false,
    total_price: true,
    unit_price: true
}

// Should print -> Total Price & Unit Price
// If three variables are true then should print -> Quantity, Total Price & Unit Price

小心,如果只有一个元素为真,它将显示
“&Unit Price”
,您可以调整它。

以下是我的尝试。在研究了约斯维尔·昆特罗的版本后,身材苗条了很多

const fmtText=obj=>Object
.keys(obj)//密钥数组
.filter(k=>obj[k])//只取真正的
.join(“,”//join找到的键与,
.replace(/g/g,“”//替换下划线
.replace(/\b([a-z])/g,x=>x.toUpperCase())//InitialCap
.替换(/,(?=[^,]*$)/,'&');//替换最后一个逗号
const conf1={数量:false,总价:true,单价:true}
const conf2={数量:真,总价:真,单价:真}
const conf3={数量:假,总价:真,单价:假}
控制台日志(fmtText(conf1))
控制台日志(fmtText(conf2))

控制台。日志(FMTTXEXT(CONT3))听起来像是在尝试动态地使用变量名,这是一个巨大的代码嗅觉——如果可能的话,考虑另一种方式。(可能是一个对象)请添加您尝试过的内容。@mplungjan如果我有很多变量,并且我只需要执行
如果
直到永恒怎么办?@CertainPerformance使用XHR请求获取,是的,它们被包装在一个对象中!您的代码根本没有任何对象。如果这不是真实的代码,请张贴真实的代码。非常优雅。我也有同样的概念,但不是像ES6那样this@mplungjan通过使用RegExp和解释,很好地回答了问题。。Thanks@mplungjan非常感谢。这是一篇典型的事后不读的文章…;-)
const confirmations = {
    quantity: false,
    total_price: true,
    unit_price: true
};

// filter out false values and return object keys as an array of strings
const validatedConfirmations = Object.keys(confirmations).filter((name) => confirmations[name]);

// make them human readable
const humanReadableConfirmations = validatedConfirmations.map(makeItHumanReadable);

// crunch it all to a single string
const lastConfirmationMessage = humanReadableConfirmations.pop();
const confirmationMessage = humanReadableConfirmation.join(', ') + ` & ${lastConfirmationMessage}`;