在数组之间交换元素

时间:2014-08-29 08:56:11

标签: javascript arrays

我正在尝试从一个数组中删除项目然后添加到另一个数组中。在某个阶段,我会将它们添加回原始数组。当我运行数组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 个答案:

答案 0 :(得分: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);
           }
      }   
 } 

答案 1 :(得分:0)

更改为forEach仍然会产生错误,直到我更改了arr.shift()而不是arr.splice(i,0)。

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