我在我的项目中得到了这段代码,但我对它不满意,因为同样的var声明正在重复。有没有更好的方法来处理它?</ p>
if (type == 1) {
var addressId = data.address.BillingAddress.id;
var addressTitle = data.address.BillingAddress.title;
var $select = $('.billingAddressId');
var $notification = $('.billingNotification');
} else {
var addressId = data.address.DeliveryAddress.id;
var addressTitle= data.address.DeliveryAddress.title;
var $select = $('.deliveryAddressId');
var $notification = $('.shippingNotification');
}
答案 0 :(得分:6)
为什么不在if-else阻止
之前声明它们var addressId, addressTitle, $select, $notification;
if ( type == 1 ) {
addressId = data.address.BillingAddress.id;
addressTitle = data.address.BillingAddress.title;
$select = $('.billingAddressId');
$notification = $('.billingNotification');
} else {
addressId = data.address.DeliveryAddress.id;
addressTitle= data.address.DeliveryAddress.title;
$select = $('.deliveryAddressId');
$notification = $('.shippingNotification');
}
答案 1 :(得分:2)
利用允许您执行此操作的Javascript,并保持原样。
答案 2 :(得分:1)
您可以使用动态属性:
var addressId = data.address[type==1 ? "BillingAddress" : "DeliveryAddress"].id,
addressTitle = data.address[type==1 ? "BillingAddress" : "DeliveryAddress"].title,
$select = $(type==1 ? '.billingAddressId' : '.deliveryAddressId'),
$notification = $(type==1 ? '.billingNotification' : '.shippingNotification');
答案 3 :(得分:1)
您可以放弃if
并使用short circuit evaluation:
var addressId = type === 1 && addressId = data.address.BillingAddress.id
|| data.address.DeliveryAddress.id;
/** ...etc **/
或使用ternary operator:
var addressId = type === 1 ? addressId = data.address.BillingAddress.id
: data.address.DeliveryAddress.id;
/** ...etc **/
答案 4 :(得分:0)
var addressId = "";
var addressTitle ="";
var $select = "";
var $notification="";
if (type == 1) {
addressId = data.address.BillingAddress.id;
addressTitle = data.address.BillingAddress.title;
$select = $('.billingAddressId');
$notification = $('.billingNotification');
} else {
addressId = data.address.DeliveryAddress.id;
addressTitle= data.address.DeliveryAddress.title;
$select = $('.deliveryAddressId');
$notification = $('.shippingNotification');
}
答案 5 :(得分:0)
在外部作用域中声明变量,以便您可以在块内访问它们。
var addressId = "";
var addressTitle = "";
var $select="";
var $notification="";
if (type == 1) {
addressId = data.address.BillingAddress.id;
addressTitle = data.address.BillingAddress.title;
$select = $('.billingAddressId');
$notification = $('.billingNotification');
} else {
addressId = data.address.DeliveryAddress.id;
addressTitle= data.address.DeliveryAddress.title;
$select = $('.deliveryAddressId');
$notification = $('.shippingNotification');
}