为什么我的函数 return 是一个不同的数组?

Why does my function return a different array?

我有一些代码用于执行以下操作:

Given two arrays of strings a1 and a2 return a sorted array r in lexicographical order of the strings of a1 which are substrings of strings of a2.
Arrays are written in "general" notation.

现在我正在做 array1 = ["arp", "live", "strong"]array2 = ["lively", "alive", "harp", "sharp", "armstrong"] 的测试。 我想我明白了,但我不明白为什么在最后一个 for 循环中我用 newArray.splice(k, k+1) 替换 newArray.splice(l, l+1) 时函数只 returns 数组 ["arp", "strong"]。 谁能告诉我这是为什么?

function inArray(array1, array2) {
    var newArray = [];
    var sortedArray = [];
    for (var i in array2) {
        for (var j in array1) {
            if (array2[i].includes(array1[j])) {
                newArray.push(array1[j]);
            };
        };
    };
    sortedArray = newArray.sort();
    for (var k = 0; k < newArray.length; k++) {
        for (var l = 0; l < newArray.length; l++) {
            if (newArray[k] === newArray[l] && k != l) {
                newArray.splice(l, l + 1)
            }
        }
    }
    return sortedArray;
};

console.log(inArray(["arp", "live", "strong"], ["lively", "alive", "harp", "sharp", "armstrong"]));

原因是 splice() 的第二个参数不是拼接的结束位置,而是应该删除的元素数。因此,当 k = 1 时,您删除了 2 个元素,而不仅仅是索引 1.

处的元素

newArray.splice(l, 1)newArray.splice(k, 1) 都可以正常工作。

function inArray(array1,array2){
 var newArray = [];
 var sortedArray = [];
  for (var i in array2) {
   for (var j in array1) {
    if (array2[i].includes(array1[j])) {
     newArray.push(array1[j]);
    };
   };
  };
  sortedArray = newArray.sort();

  for (var k = 0; k < newArray.length; k++) {
   for (var l = 0; l < newArray.length; l++) {
    if (newArray[k] === newArray[l] && k != l) {
     newArray.splice(k, 1);

    }
   }
  }
  return sortedArray;
};

console.log(inArray(["arp", "live", "strong"], ["lively", "alive", "harp", "sharp", "armstrong"]));

在评论中你已经得到了答案。尽可能使用 ES2015/ES6,受益于它的冒险。

const words1 = ["arp", "live", "strong"];
const words2 = ["lively", "alive", "harp", "sharp", "armstrong"];
const final = [];

words1.forEach(v => {
  words2.forEach(v2 => {
    if (v2.includes(v)) {
      final.push(v);
    }
  });
});

const finalSorted = [...new Set(final.sort())];

// just to add html
const pre = document.getElementById('result');

finalSorted.forEach(v => {
  let content = pre.textContent;
  content += `\n- ${v}`;
  pre.textContent = content;
});
<label>Result:</label>
<pre id="result"></pre>

看起来你有点过于复杂了 ;)

a1 = ["arp", "live", "strong", "bazooka"]
a2 = ["lively", "alive", "harp", "sharp", "armstrong"]


result = a1
    .filter(x => a2.some(y => y.includes(x)))
    .sort();

console.log(result);