对于下面的JavaScript函数,我试图找出如何降低认知复杂度的方法。
function Person(data) {
var self = this;
if (data) {
self.id = data.Id === null? "" : data.Id;
self.name = data.Name === null? "" : data.Name;
self.phone= data.Phone === null? "" : data.Phone;
self.address = data.Address=== null ? "" : data.Address;
} else {
self.id = "";
self.name = "";
self.phone = "";
self.address = "";
}
}
答案 0 :(得分:0)
也许是这样的:
function Person(data) {
var self = this;
self.id = "";
self.name = "";
self.phone = "";
self.address = "";
if (data) {
self.id = getValueOrDefault(data.Id);
self.name = getValueOrDefault(data.Name);
self.phone = getValueOrDefault(data.Phone);
self.address = getValueOrDefault(data.Address);
}
}
function getValueOrDefault(value) {
return value === null ? "" : value;
}