在数组之间交换元素

3

我试图将一个数组中的项目移除并添加到另一个数组中。在某个阶段,我将它们再次添加回原始数组。当我运行数组10次时,第10次没有返回预期的结果,全部数组= 0,移除数组= 100; 有人知道为什么会这样吗?

 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,它会创建一个数组副本。 - user663031
谢谢,直到我加上了arr.shift()它才正常工作。现在它已经按预期工作了。 - nontechguy
2个回答

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);
           }
      }   
 } 

这正是我想要做的。它不会产生对数组中对象的任何引用错误。非常感谢!!! - nontechguy

0

将循环改为forEach后,直到我将arr.shift()更改为arr.splice(i,0),错误才得以解决。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接