为什么在Javascript中> =(大于或等于)比较工作? [英] Why doesn't >= (greater than or equals) comparison work in Javascript?

查看:81
本文介绍了为什么在Javascript中> =(大于或等于)比较工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里缺少什么?这个脚本对我来说很合适。

What am I missing here? This script looks right to me.

但是出于某种原因,当我发送邮政编码为02897(或任何应该是罗德岛的邮编)时,它会返回新罕布什尔州。除了Javascript开发人员可能拥有的政治信仰(肯定大多数人更愿意住在新汉普尔而不是罗德岛),为什么这个脚本不起作用?

But for some reason when I send it a zipcode of 02897 (or anything that should be Rhode Island), it returns New Hampshire. Aside from political beliefs Javascript developers may have (sure most people would prefer to live in New Hampsire than Rhode Island), why doesn't this script work?

新泽西州和阿拉巴马州工作正常。为什么罗德岛不能得到一些爱?

New Jersey and Alabama work fine. Why can't Rhode Island get some love?

function getState(zip) {
    var thiszip = zip; // parseInt(zip);
    if (thiszip >= 35000 && thiszip <= 36999) {
            thisst = 'AL';
            thisstate = "Alabama";
            }
    else if (thiszip >= 03000 && thiszip <= 03899) {
        thisst = 'NH';
        thisstate = "New Hampshire";
        }
    else if (thiszip >= 07000 && thiszip <= 08999) {
        thisst = 'NJ';
        thisstate = "New Jersey";
        } 
    else if (thiszip >= 02800 && thiszip <= 02999) {
        thisst = 'RI';
        thisstate = "Rhode Island";
        }
    else {
        thisst = 'none';
    }
   return thisst;
}


推荐答案

03000 等于 1536 作为小数。

这是因为前导零导致值被解释为八进制。

This is because the leading zero causes the value to be interpreted as an octal.

因为最后你正在进行数值比较,为什么不在比较中省略前导零?

Since in the end you are doing number value comparisons, why not omit the leading zero in your comparison?

else if (thiszip >= 3000 && thiszip <= 3899) {

否则,使用 parseInt 并声明小数:

otherwise, use parseInt and declare decimal:

else if (thiszip >= parseInt(03000, 10) && thiszip <= parseInt(03899, 10)) {
                                 // ^^^ pass radix parameter          ^^^ pass radix parameter

你可能想要 parseInt 传入的值:

var thiszip = parseInt(zip, 10);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types
https://developer.mozilla.org/en-US/docs/Web/ JavaScript / Reference / Global_Objects / parseInt

这篇关于为什么在Javascript中&gt; =(大于或等于)比较工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆