开发者

Make array, compare and get value from it

开发者 https://www.devze.com 2023-04-12 20:26 出处:网络
What I like to achieve is this: var price = $.cookie(\'cur_price\'); //this is USD, EUR or GBP var price = \'USD\'; //this could be an outcome

What I like to achieve is this:

    var price = $.cookie('cur_price'); //this is USD, EUR or GBP
    var price = 'USD'; //this could be an outcome

        var USD = 30; //to put this in a array
        var EUR = 24; //seems the right way
        var GBP = 30;

           var active = Get from array the value where price == array value

    $('#price').html(active);

How 开发者_JS百科can you do this with jQuery?


Create an associative-array-like object to store the prices:

var price = $.cookie('cur_price'); //this is USD, EUR or GBP
var prices = {
    'USD': 30,
    'EUR': 24,
    'GBP': 30
    };
$('#price').html(prices[price]);


Instead of using an array, I would use an object literal, as it allows you to map keys to values, rather than arbitrary array indexes.

var price = $.cookie('cur_price');
var map = {
    USD: 30,
    EUR: 24,
    GBP: 30
};

var active = map[price];

$('#price').html(active);

Furthermore, to consider the case where cur_price has not been set yet (first visit?) you might want to provide a default value:

var price = $.cookie('cur_price');
var map = {
    USD: 30,
    EUR: 24,
    GBP: 30
};

if (price == null) {
    price = 'GBP';
}

var active = map[price];

$('#price').html(active);

Furthermore, be warned that JavaScript is freely edited by the client; you should be validating all input on the server as well (especially when money is involved!).


var cookie = 'EUR';
var USD = 30; //to put this in a array
var EUR = 24; //seems the right way
var GBP = 30;
var active;

switch(cookie) {
    case 'EUR':
        active = EUR;
        break;
    case 'USD':
        active = USD;
        break;
    case 'GBP':
        active = GBP;
        break;
   default:
        active = -1; // maybe?
        break;
}
$('#price').html(active);
0

精彩评论

暂无评论...
验证码 换一张
取 消