2014-08-29 53 views
3

我想從一個數組中刪除項目,然後添加到另一個。在某個階段,我會將它們添加回原始數組。當我第10次運行數組10次時,不會返回完整數組= 0的預期結果。任何人都知道爲什麼會這樣?陣列之間交換元素

var fullArr = [];//contains all items 
var remArr = [];//contains removed items 
var userAnswer = true;//this would be user input 

populateArray(); 
runTenTimes(); 
//getting the answer right 10 times should result in fullArr.length = 0; remArr.length = 100; 

function runTenTimes(){ 
    for(var i=0;i<10;i++){ 
    //console.log(i); 
    checkUserAnswer(); 
    } 
} 
function populateArray(){ 
    for(var i=0;i<100;i++){ 
     fullArr.push(i); 
    } 
} 

function checkUserAnswer(){ 
    if(userAnswer){//only if true 
     for(i=0;i<10;i++){//10 because I remove 10 at a time 
      removeShape(fullArr,fullArr[i],remArr); 
     } 
    }else{ 
      // add elements from remove arr 
      // back into full array 
    } 
    console.log("full array : " + fullArr.length); 
    console.log("remove array : " + remArr.length); 
    console.log("------------------") 
} 

function removeShape(arr,item,rem){ 
     for(var i = 0;i<arr.length; i++) { 
      if(arr[i] === item) { 
      rem.push(arr[i]); 
      arr.splice(i, 1); 
      } 
     } 
} 

http://jsfiddle.net/non_tech_guy/vy671jv4/

+2

你改變陣列,同時在遍歷它。解決這個問題的一個簡單方法是使用'forEach',它會複製數組。 – 2014-08-29 09:04:54

+0

謝謝,它仍然產生了一個錯誤,直到我添加了arr.shift()。現在它按預期工作。 – 2014-08-29 09:37:37

回答

3

請使用此代碼

var fullArr = [];//contains all items 
var remArr = [];//contains removed items 
var userAnswer = true;//this would be user input 

populateArray(); 
runTenTimes(); 
//getting the answer right 10 times should result in fullArr.length = 0; remArr.length = 100; 

function runTenTimes(){ 
    for(var i=0;i<10;i++){ 
    //console.log(i); 
    checkUserAnswer(); 
    } 
} 
function populateArray(){ 
    for(var i=0;i<100;i++){ 
     fullArr.push(i); 
    } 
} 

function checkUserAnswer(){ 
    if(userAnswer){//only if true 
     var arrCopy = fullArr.slice(0); 
     for(i=0;i<10;i++){//10 because I remove 10 at a time 
      removeShape(fullArr,arrCopy[i],remArr); 
     } 
    }else{ 
      // add elements from remove arr 
      // back into full array 
    } 
    console.log("full array : " + fullArr.length); 
    console.log("remove array : " + remArr.length); 
    console.log("------------------") 
} 

function removeShape(arr,item,rem){ 
     for(var i = 0;i<arr.length; i++) { 
      if(arr[i] === item) { 
      rem.push(arr[i]); 
      arr.splice(i, 1); 
      } 
     } 
} 
+0

那正是我想要做的。它不會對數組中的對象產生任何引用錯誤。非常感謝!!!! – 2014-08-29 10:27:36

0

改變到的forEach仍然產生的誤差,直到我改變arr.shift()而不是arr.splice(I,0)。

function removeShape(arr,item,rem){ 
     arr.forEach(function(){ 
     if(arr[i] === item) { 
      rem.push(arr.shift()); 
      } 
     }) 
}