首页 > 解决方案 > 如何对循环的结果进行循环

问题描述

我有一个返回对象数组的函数。

const matches = checkMatching(param1, param2, param3);

函数 checkMatching 返回数组,我想在该数组上调用另一个函数 checkMatching。然后,如果 checkMatchingfunction 仍然返回数组,我想在该数组上调用 checkMatching。总结我想创建无限循环,直到 chechMatching 不会返回数组;

基本上我正在尝试创建数组

let allMatchingWords = []

它从循环中收集所有结果。

目前我有这样的东西


const checkMatching = (board, r, c) => {
  const top = board[r - 1] !== undefined && { row: r - 1, column: c };
  const bottom = board[r + 1] !== undefined && { row: r + 1, column: c };
  const left = board[r][c - 1] !== undefined && { row: r, column: c - 1 };
  const right = board[r][c + 1] !== undefined && { row: r, column: c + 1 };

    const directionsWithMatches = [top, bottom, left, right]
    .filter(dir => dir instanceof Object)
    .filter(({ row, column }) => board[row][column].word === board[r][c].word);

  return directionsWithMatches;


};
const matches = checkMatching(param1, param2, param3);

let allMatchingWords = [];

 matches.map(({ row, column }) => {
    allMatchingWords = [
      ...matches,
      ...allMatchingWords,
      ...checkMatching(param1, param2, param3),
    ];
});
/// removing duplicates
 allMatchingWords = allMatchingWords.filter(
    (v, i, a) => a.findIndex(t => t.key1 === v.key1 && t.key2 === v.key2) === i,
  );

但是现在有一个循环两次的捷径。

我试图创建 while 循环,但我不确定这是否可行。

标签: javascriptarraysloopsfor-loopwhile-loop

解决方案


推荐阅读