2017-04-03 56 views
1

我有这个if语句和else块,它们都在for循环中。当我执行它时,它总是返回来自if语句和else语句的值。当if语句为false时,它不应该仅仅到else块吗?Javascript For..In循环执行if和else语句

<!DOCTYPE html> 
 
<html> 
 
<body> 
 

 
<p>Click the button to begin</p> 
 

 
<button onclick="myFunction()">Try it</button> 
 

 
<script> 
 

 
const moodList = { 
 
    sad: { 
 
     quotes: ['this is a sad quote', 
 
       'this is a sad quote number 2', 
 
       'this is a sad quote number 3' 
 
       ] 
 
    }, 
 
    happy: { 
 
     quotes: ['this is a happy quote', 
 
       'this is a happy quote number 2', 
 
       'this is a happy quote number 3' 
 
       ] 
 
    } 
 
} 
 

 
function myFunction() { 
 

 
    let moodInput = prompt('Enter a feeling'); 
 

 
    for (var key in moodList) { 
 
    if (moodInput.includes(key)) { 
 
     console.log('you got a result!'); 
 
    } else { 
 
     console.log('nothing'); 
 
    } 
 
    } 
 
} 
 
</script> 
 

 
</body> 
 
</html>

+0

它不是。你为什么认为这是?这两种方法都无法同时进行。它可能会在循环的不同迭代过程中完成每个循环,但这是不同的。 – Utkanos

+0

您正在循环每个键。如果我输入伤心,你会得到一次真实的,一次虚假的IF。 – yBrodsky

+0

您正在使用您的moodList运行循环 - 因此您可以根据所有可能性检查用户输入 - 它将记录每个modd,如果它是您输入的或不是的 – Danmoreng

回答

2

而不是创建了该对象的循环,你可以检查是否输入的值对象上的一个键:

if (moodList[moodInput]) { 
    console.log('you got a result!'); 
} else { 
    console.log('nothing'); 
} 

更新的代码:

const moodList = { 
 
    sad: { 
 
    quotes: ['this is a sad quote', 
 
     'this is a sad quote number 2', 
 
     'this is a sad quote number 3' 
 
    ] 
 
    }, 
 
    happy: { 
 
    quotes: ['this is a happy quote', 
 
     'this is a happy quote number 2', 
 
     'this is a happy quote number 3' 
 
    ] 
 
    } 
 
} 
 

 
function myFunction() { 
 
    let moodInput = prompt('Enter a feeling'); 
 
    if (moodList[moodInput]) { 
 
    console.log('you got a result!'); 
 
    } else { 
 
    console.log('nothing'); 
 
    } 
 
}
<p>Click the button to begin</p> 
 

 
<button onclick="myFunction()">Try it</button>

1

您可以使用该密钥并检查密钥是否在in operator的对象中。

const moodList = { 
 
    sad: { 
 
     quotes: ['this is a sad quote', 
 
       'this is a sad quote number 2', 
 
       'this is a sad quote number 3' 
 
       ] 
 
    }, 
 
    happy: { 
 
     quotes: ['this is a happy quote', 
 
       'this is a happy quote number 2', 
 
       'this is a happy quote number 3' 
 
       ] 
 
    } 
 
}; 
 

 
function myFunction() { 
 
    let moodInput = prompt('Enter a feeling'); 
 

 
    if (moodInput in moodList) { 
 
     console.log('you got a result!'); 
 
    } else { 
 
     console.log('nothing'); 
 
    } 
 
}
<p>Click the button to begin</p> 
 
<button onclick="myFunction()">Try it</button>

+0

非常感谢!我是一个绝对的初学者,并继续忘记何时使用以及何时不使用循环。你的例子非常感谢。 – Amos