我有以下 forEach 回圈
this.cfData.customAttributes.forEach(function (currentObj) {
if(currentObj.inputValues !== null) {
currentObj.inputValues = Array.prototype.map.call(currentObj.inputValues, function(item) { return item.value; }).join(", ");
}
if(currentObj.objectType !== null){
currentObj.objectType = currentObj.objectType.toLowerCase().replace(/(^\w{1})|(\s{1}\w{1})/g, match => match.toUpperCase());
}
if(currentObj.dataType !== null){
currentObj.dataType = currentObj.dataType.toLowerCase().replace(/(^\w{1})|(\s{1}\w{1})/g, match => match.toUpperCase());
}
if(currentObj.isGridEligible !== null){
currentObj.isGridEligible = currentObj.isGridEligible.toLowerCase().replace(/(^\w{1})|(\s{1}\w{1})/g, match => match.toUpperCase());
}
if(currentObj.isInvoiceEligible !== null){
currentObj.isInvoiceEligible = currentObj.isInvoiceEligible.toLowerCase().replace(/(^\w{1})|(\s{1}\w{1})/g, match => match.toUpperCase());
}
});
我想知道在回圈中是否有任何最短的方法來撰寫這些 if 條件?請建議。
uj5u.com熱心網友回復:
如果您允許,我將回答更通用的代碼:
- 首先,如果您使用的是單個陳述句,則可以洗掉 s
{}周圍的括號 ( )if。
objArr.forEach(obj => {
if(obj.propA !== null)
obj.propA = getPropA(obj);
if(obj.propB !== null)
obj.propB = getPropB(obj);
...
});
- 你總是可以創造一種與映射功能(過復雜的代碼
getPropA,getPropB等等)。
const getProps = {
propA(obj){ return ...; },
propB: obj => ...,
...
};
objArr.forEach(obj => {
// Object.entries receives an object, and returns an array
// in the form [ key, value ][]
for(var [ prop, getter ] of Object.entries(getProps))
if(obj[prop] !== null)
obj[prop] = getter(obj);
});
uj5u.com熱心網友回復:
我可以推薦這段代碼,它更簡單、更短。
this.cfData.customAttributes.forEach(function (currentObj) {
const arr = ["objectType", "dataType", "isGridEligible", "isInvoiceEligible"];
if (currentObj.inputValues !== null) {
currentObj.inputValues = Array.prototype.map.call(currentObj.inputValues, function (item) {
return item.value;
}).join(", ");
}
arr.forEach(item => {
if (currentObj[item] !== null) {
currentObj[item] = currentObj[item].toLowerCase().replace(/(^\w{1})|(\s{1}\w{1})/g, match => match.toUpperCase());
}
});
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/364899.html
標籤:javascript
上一篇:如何禁止物件中的密鑰
