简体   繁体   中英

Javascript - greater than/less than using 4 digits, that can start with 0?

This may sound like a dumb question, but is it possible to have a 0 at the start of a number check, and have it work?

This is what I have:

function checkCosts() {
    var date = document.getElementsByName("date")[0].value;
    var roomtype = document.getElementsByName("roomtype")[0].value;
    var night = document.getElementsByName("night")[0].value;
    var month = date.substring(0, 2);
    var year = date.substring(8, 10);
    var day = date.substring(4, 6);
    var time = month.concat(year);
    var fulldate = day.concat(time);
    if (time >= 0415 && <= 0915) {
        if (roomtype == "Classic") {
            if (night == "3") {
                document.getElementById("cost").innerHTML = "1,480";
            }
        }
    }
}

However, when I run it in jslint.com I get the following errors:

Unexpected '4' after '0'.
if(time >= 0415 && <= 0915){ 
line 9 column 28Unexpected trailing space.
if(time >= 0415 && <= 0915){ 

What's there is just one of a few different statements, all the variables will be used.

It would be possible to convert the strings into ints, but I don't know how to do this/if it will work.

A leading 0 is not the way to use ints. You should take a look here . Otherwise just use the alpabetical order using a string comparison.

There is just no need to add zeros in front of the number. If the first number identifies the level of the room just add it, where you need it.

Instead of concatenating month with year, Concatenate year with month, And then check. You need to do some modification in your logic.

function checkCosts() {
    var date = document.getElementsByName("date")[0].value;
    var roomtype = document.getElementsByName("roomtype")[0].value;
    var night = document.getElementsByName("night")[0].value;
    var month = date.substring(0, 2);
    var year = date.substring(8, 10);
    var day = date.substring(4, 6);
    var time = year.concat(month);//Concat year with month.
    var fulldate = day.concat(time);
    if (time >= 1504 && <= 1509) { //Year should be first
        if (roomtype == "Classic") {
            if (night == "3") {
                document.getElementById("cost").innerHTML = "1,480";
            }
        }
    }
}  

If you are trying to convert date to number and want to compare, use year first then month.

from this:

var time = month.concat(year);

I deduce "time" is a string.

then you should put quotes on 0415

strings are compared using alphabetical order (I hope you don't need globalization in this comparison) :

"04".concat("16") >= "0415"
 -> true
"04".concat("14") >= "0415"
 -> false

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