使用if/else在Javascript中定义常量
我在函数中使用const来定义几个变量,如下所示使用if/else在Javascript中定义常量,javascript,if-statement,constants,Javascript,If Statement,Constants,我在函数中使用const来定义几个变量,如下所示 const printBlock.format({ name : this.matchedData.clientName, date : this.matchedData.jobDate, destination : this.matchedData.address, apartment : this.matchedData.address2, stateZip : this.matchedData.zipcode }) 从
const printBlock.format({
name : this.matchedData.clientName,
date : this.matchedData.jobDate,
destination : this.matchedData.address,
apartment : this.matchedData.address2,
stateZip : this.matchedData.zipcode
})
从那时起,我打印出所有这些东西,以便它们被声明。但是,有些数据没有公寓号码,因此显示为:
无名氏
2018年6月6日
Testdemo大道135号
空的
纽约11111
是否可以在声明常量中使用if函数,以便:
if (this.matchedData.address2 == null){
//Do nothing
} else {
apartment : this.matchedData.address2,
}
不,但是你可以用
不,但是你可以用
您可以使用并检查属性,如果不是null
,则获取一个对象进行赋值
printBlock(Object.assign(
{
name: this.matchedData.clientName,
date: this.matchedData.jobDate,
destination: this.matchedData.address,
apartment: this.matchedData.address2,
stateZip: this.matchedData.zipcode
},
this.matchedData.address2 === null || { apartment: this.matchedData.address2 }
));
您可以使用并检查属性,如果不是null
,则获取一个对象进行赋值
printBlock(Object.assign(
{
name: this.matchedData.clientName,
date: this.matchedData.jobDate,
destination: this.matchedData.address,
apartment: this.matchedData.address2,
stateZip: this.matchedData.zipcode
},
this.matchedData.address2 === null || { apartment: this.matchedData.address2 }
));
您可以先创建不带单元项的对象,然后添加单元项(如果它不为null)
const a = {
name : this.matchedData.clientName,
date : this.matchedData.jobDate,
destination : this.matchedData.address,
stateZip : this.matchedData.zipcode
};
if (this.matchedData.address2 !== null){
a.apartment : this.matchedData.address2;
}
您可以先创建不带单元项的对象,然后添加单元项(如果它不为null)
const a = {
name : this.matchedData.clientName,
date : this.matchedData.jobDate,
destination : this.matchedData.address,
stateZip : this.matchedData.zipcode
};
if (this.matchedData.address2 !== null){
a.apartment : this.matchedData.address2;
}
const printBlock({…})
将引发错误,因为它不是初始化常量的有效方法。如果printBlock
是一个函数,为什么不处理printBlock
主体中的空值呢
function printBlock(obj) {
for (var prop in obj) {
if (obj[prop]) {
console.log(obj[prop]); // or do whatever you mean by 'print'
}
}
}
const printBlock({…})
将引发错误,因为它不是初始化常量的有效方法。如果printBlock
是一个函数,为什么不处理printBlock
主体中的空值呢
function printBlock(obj) {
for (var prop in obj) {
if (obj[prop]) {
console.log(obj[prop]); // or do whatever you mean by 'print'
}
}
}
const printBlock({…})
是一个语法错误。你到底在做什么?constprintblock({…})
是一个语法错误。你到底在做什么?这种方法也会创建一个属性,即使它是空的。这是对我有效的解决方案!我最后格式化如下:单元:((this.matchedData.address2!==null)?this.matchedData.address2:“”)
这种方法还将创建一个属性,即使它为null。这是对我有效的解决方案!我最后格式化如下:单元:((this.matchedData.address2!==null)?this.matchedData.address2:“”)