如何使字符串不可附加?

时间:2017-06-14 14:24:47

标签: javascript jquery

这甚至可能吗?

function from_country_to_country(country_from, country_to) {
    // get the right zone prices
    var zone_price = zone_finder(country_to['zone']);
    $('#country_to_country').html(country_from['land']);
    $('#call').html(formatPrice(country_from[zone_price]) + ' kr/min');
    $('#recieve').html(formatPrice(country_from['receive_calls']) + ' kr/min');
    $('#send_sms').html(formatPrice(country_from['send_sms']) + ' kr/SMS');
    $('#recieve_sms').html(formatPrice(country_from['receive_sms']) + ' kr/SMS');
    $('#opening_fee').html(formatPrice(country_from['opening_fee']) + ' kr');
}

function within_the_country(country) {
    $('#from_within').html(country['land']);
    $('#from_domestic').html(formatPrice(country['domestic']) + ' kr/min');
    $('#from_RCF').html(formatPrice(country['receive_calls']) + ' kr/min');
    $('#from_send_sms').html(formatPrice(country['send_sms']) + ' kr/SMS');
    $('#from_recieve_sms').html(formatPrice(country['receive_sms']) + ' kr/SMS');
    $('#from_opening_fee').html(formatPrice(country['opening_fee']) + ' kr');
    $('#from_gprs_data').html(formatPrice(country['data_price'])+ ' kr/mb');
}

// Format prices from ex: turns 1 into 1,00
function formatPrice(n) {
    if (!isNaN(parseFloat(n))) {
        n = parseFloat(n);
        n = Math.round(n * 100) / 100
        n = n.toFixed(2);
        return n;
    } else {
       // IF WE CAN MAKE "n" NON-APPENDABLE HERE 
        return n;
    }
}

如果n不是数字,我不希望将' kr/mb'附加到字符串中。我知道我可以检查它是否是一个数字,如果没有,不要追加。但是我有许多不同的后缀,我追加到formatPrice()的返回字符串。那么我需要在任何地方检查这个。有一个很好的工作吗?

1 个答案:

答案 0 :(得分:3)

调整formatPrice功能以有条件地接收单位:

function formatPrice(n, unit) {
  if(!isNan(...)) { 
    ... 
    return n + " " + unit; 
  } 
  else { 
    return n;  
  } 
} 

formatPrice(500, 'kr/mb');