2011-03-04 26 views
0

我需要打印出第二個數組,它從第一個數組中獲取數字。如果第二個數組有重複項,它將只打印一次數字。我現在的代碼打印第一個數組的最後一個數字20次....我不能爲我的生活找出如何做到這一點。我討厭用簡單的家庭作業問題來到這裏,但導師沒有幫助。如果你能幫助我,請包括一些評論與你在做什麼,我想學習這個!創建一個包含20個數字的數組,只要它們不是重複的,使用最小的數組打印每個數值?

<html> 
<head> 
<title> HW 10.12 </title> 
<script type="text/javascript"> 

var array=new Array(19); 
var array2 =new Array(); 

for(var j=0; j< array.length; j++) 
{ 
array[j]=Math.floor(10 + Math.random()*100); 
} 

for (var i=0; i < array.length; i++) 

for(var k=0; k < array.length; k++) 
{ 
if (array2[k] != array[i]) 
{ 
array2[k] = array[i]; 
}} 


document.writeln(array2) 

</script> 
</head> 
<body> 
</body> 
</html> 

回答

0

更改JavaScript來如下:

var array = new Array(19); 
var array2 = new Array(); 

for (var j = 0; j < array.length; j++) { 
    array[j] = Math.floor(10 + Math.random() * 100); 
} 

var isDuplicate = false;  
for (var i = 0; i < array.length; i++) { 
    isDuplicate = false; 
    for (var k = 0; k < array.length; k++) { 
     if (array2[k] == array[i]) { //Check if this current value of array1 exists in array2 
     //If yes then we should ignore this value 
     // hence mark isDuplicate as true. 
      isDuplicate = true; 
      break; //Break from loop as we don't need to check any further 
     } 

    } 
    if(!isDuplicate) //if isDuplicate is not true this value is unique. Push it to array2 
     array2.push(array[i]); 
} 

document.writeln(array2) 
+0

謝謝你,你的答案是非常有幫助! – Craig 2011-03-04 06:52:14

1

我將是超級有用的今天,只是因爲它是星期五:

var array=new Array(19); 
var array2 =new Array(); 

// Nothing changed here, just some formatting... 
for(var j = 0; j < array.length; j++) { 
    array[j]=Math.floor(10 + Math.random()*100); 
} 

// Declare a function variable. The function will determine 
// whether a value is already contained in the array or not. 
var hasValue = function(val,arr) { 
    // Loop through the array "arr" (passed through as parameter) and 
    // determine whether the value "val" (also passed through as parameter) 
    // already exists in the array. If it does, return "true". 
    for (var i = 0; i < arr.length; i++) { 
    if (arr[i] == val) 
     return true; 
    } 
    // If, after looping through all items in the array, the value isn't found, 
    // return "false". 
    return false; 
}; 

// Loop through the original array. 
for (var i = 0; i < array.length; i++) { 
    // Call the "hasValue" function to determine whether the current item in the 
    // original array already exists in the new array. If it doesn't, add it to 
    // the new array. 
    if (!hasValue(array[i],array2)) 
    array2.push(array[i]); 
} 

// Nothing changed here... 
document.writeln(array2); 
+0

+1。因爲這是星期五 – Ben 2011-03-04 06:37:13

+0

非常感謝,這有助於很多!我沒有考慮使用布爾值。 – Craig 2011-03-04 06:52:46

+0

如果您發現它有幫助,您可以提出我的答案...:P – FarligOpptreden 2011-03-04 06:54:32

相關問題