简体   繁体   中英

Javascript - Compare value to Associative array index

I have the following code:

var license_price = 0;
    var num_licenses = jQuery('#num_licenses').val();
    var lp = {};

                lp[1]=12.50;
                lp[10]=15.50;
                lp[50]=50.00;

    for(var index in lp) {alert(index);
        if (num_licenses >= index){
            license_price = parseFloat(lp[index]);
        }
    }
    //alert(license_price);
    jQuery('#total_price').val((num_licenses * license_price));

This code determines the value entered in the num_licenses box, then goes through the array lp and assigns a price based on the value of each key. So, if num_licenses = 8, the price should be 12.50 each, if the num_licess = 60, the price should be $60.

It works for all values except 2 - 9. If I enter 2-9, the price from fp[10] is used. But, if it is 1, then I get 12.50.

take care, lee

When you iterate over the object's indices they are typed as strings. Your > comparison is actually sorting them alphabetically rather than numerically. Parse its numeric value to get this working. (alphabetically '2' occurs after all values starting with '1', including '10', so '2' > '10', etc.)

for(var index in lp) {
    alert(index);
    if(lp.hasOwnProperty(index)) { // prevent comparison when property inherited
        if (num_licenses >= parseInt(index,10) ){
            license_price = parseFloat(lp[index]);
        }
    }
}

The problem is that you are comparing a string to an integer. The result of the val() function is a string. Therefore, if your input is '2' , the result of '2' <= 10 is false. You should convert it first to an integer using the parseInt() function.

Here's what it should look like:

var license_price = 0;
var num_licenses = parseInt(jQuery('#num_licenses').val(),10);
var lp = {};

            lp[1]=12.50;
            lp[10]=15.50;
            lp[50]=50.00;

for(var index in lp) {alert(index);
    if (num_licenses >= index){
        alert("Greater than " + index);//added this for debugging
        license_price = parseFloat(lp[index]);
    }
}
//alert(license_price);
jQuery('#total_price').val((num_licenses * license_price));

Note that I added a parseInt() call to the value. I also added some alert calls so you can see what is happening.

Here is a link to a jsFiddle snippet so that you can test it out: http://jsfiddle.net/CmbvW/8/

In your code lp is a Object not a array, so index is a property name with type String.

Try to change your code to

var lp = [];

then the index will be a number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM