简体   繁体   English

条件循环无法按预期工作

[英]Conditional loop not working as expected

I am following courses in FreeCodeCamp to learn Javascript. 我正在FreeCodeCamp的课程中学习Javascript。 I am in "Diff in Two Arrays". 我在“两个数组的差异”中。 Assignment is comparing two arrays and return a new array with any items only found in one of the two given arrays, but not both. 分配比较两个数组,并返回一个新数组,其中包含仅在两个给定数组之一中找到的所有项目,但不是两个都返回。

Below is the code I try to compare them, second part does not apply. 下面是我尝试比较它们的代码,第二部分不适用。 I want to undertand why second part of the conditional loop does not work. 我想理解为什么条件循环的第二部分不起作用。

function diffArray(arr1, arr2) {
  var filtered = [];
  var l = 0;
  newArr = Array.prototype.slice.call(arguments);
  for (var j=0; j < newArr.length; j++){
    for (var k=0; k < newArr[j].length; k++){
       //values to check before and next index 
       l  = j + 1;
       var m = j-1;
       if (l < newArr.length){
            if (newArr[l].indexOf(newArr[j][k]) === -1){
                filtered.push(newArr[j][k]);
            } else if (j == newArr.length - 1){ // this part does not work
                console.log(j);
                if (newArr[m].indexOf(newArr[j][k]) === -1 ){
                    console.log(newArr[j]);
                    filtered.push(newArr[l][k]);
                }
            }        
         }
       }
    }
  // Same, same; but different.
  return filtered;
}

diffArray([1, "calf", 3, "piglet"], [1, "calf", 3, 4]);

Thanks. 谢谢。

You can do this way : 您可以这样做:

var arr1 = [1,2,34,5,6,7,8,9];
var arr2 = [1,2,3,4,5,6,7,8,9];
var diff = arr1.concat(arr2).sort().filter((x, index, arr) => (x != arr[index+1] && x != arr[index-1]));
console.log(diff); // [ 3, 34, 4 ]

This is my way to solve this problem,hope it can help you. 这是我解决此问题的方法,希望它可以为您提供帮助。 first I loop arr1,and see can it found some match in arr2 and push it in newArr second I do the same thing as first step,but reverse arr1 and arr2,and push it newArr. 首先,我循环arr1,看看它是否能在arr2中找到匹配项并将其推入newArr。

function diff(arr1, arr2) {
  var newArr = [];

  for(var i=0;i<arr1.length;i++){
      if(arr2.indexOf(arr1[i])<0){
        newArr.push(arr1[i]);
      }
  }
  for(var j=0;j<arr2.length;j++){
    if(arr1.indexOf(arr2[j])<0){
      newArr.push(arr2[j]);
    }
  }
  return newArr;
}
console.log(diff); // [ 3, 34, 4 ]

diff([1, 2, 3, 5], [1, 2, 3, 4, 5]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM