debugging 调用函数时数组发生更改(调试)

mnemlml8  于 2023-02-09  发布在  其他
关注(0)|答案(1)|浏览(145)
console.clear();
function hori_resolveOverlaps(lines) {
  if (lines.length <= 1) return lines;

  // Sort the lines ascending by start value
  lines.sort((a, b) => a[0][0] - b[0][0]);

  let outLines = [lines[0]];
  let last = outLines[0];
  // Iterate over the lines, skipping the first one
  lines.slice(1).forEach((line) => {
    // There's an overlap, so extend the current segment's end
    if (line[0][0] <= last[1][0]) {
      last[1][0] = Math.max(last[1][0], line[1][0]);
    } else {
      // No overlap, start a new segment
      outLines.push(line);
      last = outLines[outLines.length - 1];
    }
  });
  return outLines;
}
const input=[ [[1,4],[40,4]] , [[1,5],[40,5]] , [[4,7],[4,24]] , [[1,9],[4,1]] , [[1,2],[6,4]] , [[4,1],[4,2]] , [[4,35],[4,29]] , [[4,28],[4,35]] , [[30,4],[190,4]] , [[5,3.6],[9,5.2]] , [[1,20],[30,1]] , [[15,10.82758],[20,7.55172]]  ];

// a function to get the slope and intercept of the line formed by a pair of points
function describeLine([[x1, y1], [x2, y2]]) {
  if (x1 == x2) { // vertical line
    return {m: "vertical", x: x1}
  }
  const p1 = x1 > x2 ? { x: x1, y: y1 } : { x: x2, y: y2 }
  const p2 = x1 < x2 ? { x: x1, y: y1 } : { x: x2, y: y2 }
  
  const m = (p1.y - p2.y) / (p1.x - p2.x)
  const y = y1 - m * x1
  return { m, y }
}
const maps = input.reduce((acc, line) => {
    const desc = describeLine(line)
    const m = acc[desc.m] || { }
    if (desc.x) { // vertical line
      x = m[desc.x] || []
      return { ...acc, [desc.m]: { ...m, [desc.x]: [ ...x, line ]}}
    } else {
      y = m[desc.y] || []
      return { ...acc, [desc.m]: { ...m, [desc.y]: [ ...y, line ]}}
    }
}, {})
const sameLines = Object.values(maps).flatMap(Object.values)
console.log(sameLines)
console.log(hori_resolveOverlaps(sameLines[0]) )

如果没有调用hori_resolve_Overlaps,这意味着您可以使用(//),以防止它运行,在其第一个索引数组处,对长度为7的sameLines数组,下面突出显示的值莫名其妙地发生了变化.我可以知道如何解决这个bug吗?为什么sameLines数组可以在hori_resolve_Overlaps时发生变化()函数被调用?任何帮助都将不胜感激:)

console.log(sameLines)
console.log(hori_resolveOverlaps(sameLines[0]) )
我曾尝试在hori_resolve_Overlaps()函数的开头更改或清除变量作用域,但它没有解决这个问题。

nlejzf6q

nlejzf6q1#

该错误是因为hori_resolveOverlaps函数的输入是可变的,这意味着对输入所做的任何更改将在函数调用后持续存在。换句话说,传递给hori_resolveOverlaps函数的lines数组与sameLines[0]数组是内存中的同一对象,因此对lines所做的任何更改也将反映在sameLines[0]中。
为了防止这种情况,可以在将输入传递给函数之前对其进行复制,例如使用Array.slice或Array.map。这样,原始数组保持不变,函数仅对数据的副本进行操作。

const sameLines = Object.values(maps).flatMap(Object.values)
const copyOfSameLines0 = sameLines[0].slice();
console.log(hori_resolveOverlaps(copyOfSameLines0))

相关问题