首页 > 解决方案 > 从两个数组中返回一个不重复的值到一个数组中 - JavaScript ES5

问题描述

我正在尝试获得返回结果

["a", "to", "past", "adventure", "of"]

["a", "link", "to", "the", "past"]
["the", "adventure", "of", "link"]

我的返回结果是

["a", "link", "to", "the", "past", "the", "adventure", "of", "link"]

我尝试使用 .includes 方法,但我得到了更古怪的回报。我肯定错误地使用了语法。我不允许使用 .filter

我的代码

function difference(first, second) {
  const newArray = [];
  for (let i = 0; i < first.length; i++) {
    if (first[i] !== second[i]) {
      newArray.push(first[i]);
    }
  }
  for (let j = 0; j < second.length; j++) {
    if (second[j] !== first[j]) {
      newArray.push(second[j]);
    }
  }
  console.log(newArray);
  return newArray;
}

标签: javascriptarraysfor-loopecmascript-5

解决方案


推荐阅读