2016-05-31 1 views
0

저는 무작위로 생성 된 숫자에 따라 임의의 타운을 얻을 수있는 프로젝트를 진행하고 있습니다. 그러나 "마을 설립"버튼을 누를 때마다 나는 항상 "부유하다". 원하는 결과를 얻기 위해 코드를 수정하려면 어떻게해야합니까?난수 발생기가 항상 내게주는 이유는 무엇입니까?

<!DOCTYPE html> 
<html> 
<body> 
<style> 
h1 {font-size: 20pt; color: red;} 
    p {font-size: 17pt; color: blue;} 
    p2 {font-size: 18pt; color: orange;} 
    p3 {font-size: 18pt; color: green;} 
</style> 
<p>This program will create a random town upon the click of a button.</p> 

<button onclick="numberdescription()">Establish Township</button> 
<br /><br /><br /> 
<p3 id="random"></p3> 

<script> 

function numberdescription() { 
var num = Math.floor(Math.random() * 3 + 1) 
    if (num = 1) { 
     desc = "wealthy"; 
    } else if (num = 2) { 
     desc = "middle wealth"; 
    } else { 
     desc = "dirt poor"; 
    } 
document.getElementById("random").innerHTML = desc; 
} 
</script> 

</body> 
</html> 
+7

당신은'='(비교)의'='(할당) intead와 비교하고 있습니다. 따라서'if' 술어는 실행될 때'num'을'1'로 설정합니다. – Pointy

+0

필수 JavaScript 한 줄 : document.getElementById ("random") innerHTML = [ "부유 한", "중간 부", "먼지 가난한"] [Math.random() * 3)]' . 진짜 질문은 왜 동등한 수의 흙이 부족하고 부유 한 마을입니까? – Pluto

답변

2

=assignment operator으로 간주됩니다. 당신은 따라서 당신이 = 하나를 교체 코드

num = 1 

와 NUM 1의 값을 할당되어, 하나의 = 기호 값을 할당하는 comparison operator

function numberdescription() { 
    var num = Math.floor(Math.random() * 3 + 1) 
    if (num == 1) { 
     desc = "wealthy"; 
    } else if (num == 2) { 
     desc = "middle wealth"; 
    } else { 
     desc = "dirt poor"; 
    } 
    document.getElementById("random").innerHTML = desc; 
} 
+1

할당 연산자가 * 할당 연산자이므로 "대입 연산자"로 간주됩니다. – Pointy

관련 문제