简体   繁体   English

Javascript开关大于/小于运算符不起作用

[英]Javascript switch greater than / less than operators not working

The following code gets a screen resolution and works - the variable ScreenWidth contains the correct values yet the case greater than ">" and less than "<" do not work and the code always displays the default image. 下面的代码获得屏幕分辨率并起作用-变量ScreenWidth包含正确的值,但是大于“>”和小于“ <”的大小写不起作用,并且该代码始终显示默认图像。 Changing the first case to "case (ScreenWidth = 800):" does indeed work. 确实可以将第一种情况更改为“ case(ScreenWidth = 800):”。 I have also tried using "switch (TRUE)" which does absolutely nothing at all, not even the default case. 我也尝试过使用“ switch(TRUE)”,它根本不执行任何操作,甚至没有默认情况。

So my question is "Why are the greater than / less than operators not working?" 所以我的问题是“为什么大于/小于运算符不起作用?”

<script type="text/javascript">
var ScreenWidth;
ScreenWidth = (screen.width);

switch (ScreenWidth)
{
    case (ScreenWidth > 799): 
        ShowImage = ('Big.jpg');
    break;

    case (ScreenWidth < 800):
        ShowImage = ('Small.jpg');
    break;

    default :
        ShowImage = ('Default.jpg');
}

</script>

Why are the greater than / less than operators not working? 为什么大于/小于运算符不起作用?

Because you are comparing a number ( ScreenWidth ) against a boolean ( ScreenWidth > 799 ). 因为您正在将数字ScreenWidth )与布尔值ScreenWidth > 799 )进行比较。 switch compares the values using strict comparison for equality testing, so comparing different data types will always result in false . switch使用严格比较来比较值以进行相等性测试,因此比较不同的数据类型将始终导致false

Changing the first case to case (ScreenWidth = 800): does indeed work. 将第一种情况更改为case (ScreenWidth = 800):确实有效。

That's because = is an assignment and the result of ScreenWidth = 800 is 800 , so you are comparing against a number, which is fine. 那是因为=是一个赋值,并且ScreenWidth = 800的结果是800 ,所以您要与一个数字进行比较,这很好。

I have also tried using "switch (TRUE)" which does absolutely nothing at all, not even the default case. 我也尝试过使用“ switch(TRUE)”,它根本不执行任何操作,甚至没有默认情况。

Well, TRUE does not exist in JavaScript. 好吧,JavaScript中不存在TRUE JS is case-sensitive . JS 区分大小写 switch(true) should work fine. switch(true)应该可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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