Javascript 切换大于/小于运算符不工作
Javascript switch greater than / less than operators not working
以下代码获取屏幕分辨率并有效 - 变量 ScreenWidth 包含正确的值,但大于“>”和小于“<”的情况不起作用,代码始终显示默认图像。将第一种情况更改为 "case (ScreenWidth = 800):" 确实有效。我也尝试过使用 "switch (TRUE)",它什么都不做,甚至默认情况下也不做。
所以我的问题是"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?
因为您正在比较 number (ScreenWidth
) 与 boolean (ScreenWidth > 799
)。 switch
使用 严格比较 比较值进行相等性测试,因此比较不同的数据类型总是会得到 false
.
Changing the first case to case (ScreenWidth = 800):
does indeed work.
那是因为 =
是一个赋值,而 ScreenWidth = 800
的结果是 800
,所以你正在与一个数字进行比较,这很好。
I have also tried using "switch (TRUE)" which does absolutely nothing at all, not even the default case.
嗯,TRUE
在 JavaScript 中不存在。 JS 区分大小写。 switch(true)
应该可以正常工作。
以下代码获取屏幕分辨率并有效 - 变量 ScreenWidth 包含正确的值,但大于“>”和小于“<”的情况不起作用,代码始终显示默认图像。将第一种情况更改为 "case (ScreenWidth = 800):" 确实有效。我也尝试过使用 "switch (TRUE)",它什么都不做,甚至默认情况下也不做。
所以我的问题是"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?
因为您正在比较 number (ScreenWidth
) 与 boolean (ScreenWidth > 799
)。 switch
使用 严格比较 比较值进行相等性测试,因此比较不同的数据类型总是会得到 false
.
Changing the first case to
case (ScreenWidth = 800):
does indeed work.
那是因为 =
是一个赋值,而 ScreenWidth = 800
的结果是 800
,所以你正在与一个数字进行比较,这很好。
I have also tried using "switch (TRUE)" which does absolutely nothing at all, not even the default case.
嗯,TRUE
在 JavaScript 中不存在。 JS 区分大小写。 switch(true)
应该可以正常工作。