我需要检查一个变量是否大于4个其他变量。
有没有办法做到这一点?
到目前为止,我已经尝试过
if(Guitar > Percussion || Brass || Keyboard || Woodwind)
{
var guitarpage = document.getElementById("GuitarPage");
guitarpage.style.display ="block";
}
if(Percussion > Guitar || Brass || Keyboard || Woodwind)
{
var percussionpage = document.getElementById("PercussionPage");
percussionpage.style.display ="block";
}
if(Brass > Percussion || Guitar || Keyboard || Woodwind) {
var brasspage = document.getElementById("BrassPage");
brasspage.style.display ="block";
}
if(Keyboard > Percussion || Guitar || Brass || Woodwind) {
var keyboardpage = document.getElementById("KeyboardPage");
keyboardpage.style.display ="block";
}
if(Woodwind > Percussion || Guitar || Keyboard || Brass) {
var woodpage = document.getElementById("WoodwindPage");
woodpage.style.display ="block";
}
以及使用&&,但我要么显示每个div,要么根本不显示。
最佳答案
Guitar > Percussion || Brass || Keyboard || Woodwind
评估为
(Guitar > Percussion) || Brass || Keyboard || Woodwind
如果
Guitar > Percussion
或Brass
,Keyboard
和Percussion
中的第一个虚假值,则为true。您想要的是
(Guitar > Percussion && Guitar > Brass && Guitar > Keyboard && Guitar > Woodwind)
。更好的是,您可以这样做:var vals = [Guitar, Percussion, Brass, Keyboard, Woodwind];
var pageNames = ["GuitarPage", "PercussionPage", "BrassPage", "KeyboardPage", "WoodwindPage"];
var max = Math.max.apply(null, vals);
var index = vals.indexOf(max);
if (vals.indexOf(max, index + 1) == -1) {
var pageName = pageNames[index];
var page = document.getElementById(pageName);
page.style.display = "block";
}
编辑:
if
检查是否还有一个也是max
的第二个值,在这种情况下避免进行该操作;这使其等效于OP的代码。