JavaScript经典面试题:判断两个矩形是否重叠

2018-02-0306:15:11WEB前端开发Comments12,669 views2字数 594阅读模式

题目:用一个对象的数据来表示一个矩形的位置和大小:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/461.html

{
  x: 100,
  y: 100,
  width: 150,
  height: 250
}

它表示一个宽为 150 高为 250 的矩形在页面上的 (100, 100) 的位置。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/461.html

请你完成一个函数 isOverlap 可以接受两个矩形作为参数,判断这两个矩形在页面上是否重叠。例如:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/461.html

const rect1 = { x: 100, y: 100, width: 100, height: 100 }
const rect2 = { x: 150, y: 150, width: 100, height: 100 }
isOverlap(rect1, rect2) // => true

答案:文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/461.html

// 原理:http://www.geeksforgeeks.org/find-two-rectangles-overlap/
const isOverlap = (rect1, rect2) => {
  const l1 = { x: rect1.x, y: rect1.y }
  const r1 = { x: rect1.x + rect1.width, y: rect1.y + rect1.height }
  const l2 = { x: rect2.x, y: rect2.y }
  const r2 = { x: rect2.x + rect2.width, y: rect2.y + rect2.height }
  if (
    l1.x > r2.x ||
    l2.x > r1.x ||
    l1.y > r2.y ||
    l2.y > r1.y
  ) return false
  return true
}
文章源自菜鸟学院-https://www.cainiaoxueyuan.com/gcs/461.html
  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/gcs/461.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定