2015-11-24 97 views
-1

我是JavaScript新手。下面是簡單的程序,我試圖顯示我創建的數組中的元素。這是行不通的。任何人都可以讓我知道我在做什麼錯了嗎?未在Javascript中顯示數組元素

<!DOCTYPE html> 
<head> 
    <meta charset="utf-8"> 
    <title>Javascript Excercises - Functions</title> 
    <script>    
     function findPrimeFactors(){ 
      var primefacts = []; 
      var primefacs; 
      var unum = prompt("Please enter a positive number"); 
      var i = 2; 
      var num = parseInt(unum); 

      if (num > 0) {    


       while (num >= i){ 
        if (num % i == 0){ 
         primefacts.push(i); 
         num = num/i; 

         console.log("Prime factor: " + i + " New num: " + num + " Array length: " + primefacts.length + " Last array element: " + primefacts[primefacts.length-1]); 
        } 
        else { 
         i += 1; 
        } 

       }; 


       if (primefacts.length = 0) { 
        document.write("No prime factors other than 1 for this number."); 
       } 
       else { 
        primefacs = primefacts.join(); 
        console.log("Prime factors: " + primefacts[0] + ", " + primefacts[1] + ", " + primefacts[2]); 
        document.write("The prime factor for " + unum + " are : " + primefacs); 
       } 

      } 
     } 
    </script> 
</head> 
<body>   
    <button onclick="findPrimeFactors()">Click to proceed</button> 
</body> 

+0

你可以添加你的工作代碼[小提琴](http://jsfiddle.net/)?該代碼格式不好,很難遵循。 – Trasiva

+0

對不起,你能詳細說明一下嗎?不知道你的意思。 – Shilpa

+0

點擊我在前面的評論中的鏈接,你會明白我的意思。 – Trasiva

回答

1

取代: -

if (primefacts.length = 0) { 

if (primefacts.length == 0) { 

您正在設置length爲0,而不是比較。

function findPrimeFactors() { 
 
    var primefacts = []; 
 
    var primefacs; 
 
    var unum = prompt("Please enter a positive number"); 
 
    var i = 2; 
 
    var num = parseInt(unum); 
 

 
    if (num > 0) { 
 

 

 
    while (num >= i) { 
 
     if (num % i == 0) { 
 
     primefacts.push(i); 
 
     num = num/i; 
 

 
     console.log("Prime factor: " + i + " New num: " + num + " Array length: " + primefacts.length + " Last array element: " + primefacts[primefacts.length - 1]); 
 
     } else { 
 
     i += 1; 
 
     } 
 

 
    }; 
 

 

 
    if (primefacts.length == 0) { 
 
     document.write("No prime factors other than 1 for this number."); 
 
    } else { 
 
     primefacs = primefacts.join(); 
 
     console.log("Prime factors: " + primefacts[0] + ", " + primefacts[1] + ", " + primefacts[2]); 
 
     document.write("The prime factor for " + unum + " are : " + primefacs); 
 
    } 
 

 
    } 
 
}
<button onclick="findPrimeFactors()">Click to proceed</button>

+0

如果您花了一點時間來查看代碼,那麼存在更多的問題。 – Trasiva

+0

照顧詳細?是的,但只有在日誌中獲得*工作*的代碼並寫入數字,那麼**就是問題。小提琴 - http://jsfiddle.net/808ym7fk/ – BenG

+0

這實際上並沒有解決按鈕調用失敗的問題。解決這個問題,編輯你的答案以反映它,並且我會扭轉我的失望。 – Trasiva