我正在使用replace方法替换一些文本,例如: -
let data = "My name is [[employeeName]]";
data.replace('[[employeeName]]', this.employee.employeeName);
现在我关注的是员工object
,null
,如果是null
,那么上面的代码就会失败。所以我想把条件设置成这样的东西:
{this.employee ? this.employee.employeeName : ''}
如何在replace()
方法中添加条件?
请帮助我
答案 0 :(得分:3)
使用
(this.employee && this.employee.employeeName) || "";
即
data.replace('[[employeeName]]', (this.employee && this.employee.employeeName) || "" );
注意强>
[[employeeName]]
和""
中的任何一个this.employee
时,这会将this.employee.employeeName
替换为undefined
。 即,如果您的对象是
var obj = {};
data.replace('[[employeeName]]', (obj.employee && obj.employee.employeeName) || "" ); //will still replace [[employeeName]] with ""
和
var obj = { employee : {} };
data.replace('[[employeeName]]', (obj.employee && obj.employee.employeeName) || "" ); //will still replace [[employeeName]] with ""
但如果employeeName
存在
var obj = { employee : { employeeName : "emp" } };
data.replace('[[employeeName]]', (obj.employee && obj.employee.employeeName) || "" ); //will replace [[employeeName]] with "emp"
答案 1 :(得分:2)
最简单的方法是添加一个'OR'评估,并检查员工对象也不为空:
data.replace('[[employeeName]]', this.employee ? this.employee.employeeName || "" : "");
如果employee为null,或者employee name为null,则将替换为空字符串。
答案 2 :(得分:0)
如果你真的想使用三元表达式:
let name = this.employee? this.employee.employee.name: '';
let data = "My name is [[employeeName]]";
data.replace('[[employeeName]]', name);
或者只是将你的代码放在if else语句中:
如果你这样做,你实际上并不需要替换功能:
if(!(typeof employee ==="undefined")){
let data= "My name is "+ this.employee.employeeName;
}
else{
let data = "My name is nobody";
}