我最近参加了一个全栈课程。到目前为止,它进行得很好(尽管它真的很难),即使是在JS,我过去经常被困在那里。嗯,这就是我所想的,现在我完全迷失在练习中了。
谁能检查一下这把小提琴,告诉我我的错误在哪里?
练习的目标是创建一个类(矩形),一种检查碰撞的方法(这没问题),我有问题的部分是我需要检查1000个任意大小的矩形的碰撞,他们的创建是好的,但检查是我卡住的地方。
let randomRect = [];
let collRect = [];
function colCheck(n) {
for (let i = 0; i < n; i++) {
randomRect[i] = Rectangle;
Rectangle = {};
Rectangle.name = "Rectangle " + i;
Rectangle.topLeftXPos = Math.floor(Math.random() * 10);
Rectangle.topLeftYPos = Math.floor(Math.random() * 10);
Rectangle.width = Math.floor(Math.random() * 10);
Rectangle.length = Math.floor(Math.random() * 10);
randomRect.push(Rectangle);
}
for (let j = 0; j > n; j--) {
if (randomRect[i].collides(randomRect[j])) {
collRect.push(Rectangle);
console.log("Collision detected")
}
}
}
colCheck(1000);
console.log(collRect);collides方法在jsfiddle上。如果我犯了一些拼写错误,我很抱歉。
这是我的小提琴:https://jsfiddle.net/ou5wyrp8/3/
发布于 2021-09-14 07:23:44
您好,我开始做一些编辑,以推动您在正确的方向。您的第一个错误是您尝试使用类的方式。在从类创建对象时,您希望使用new关键字、类名,然后将类名视为函数。请注意,使用new时执行的函数是构造函数,例如
let newRect = new Rectangle(topLeftXPos, topLeftYPos, width, length)接下来,在for循环中出现了问题。对于初学者,我假设您希望j循环嵌套在i循环中,但事实并非如此。
我尽可能地解决了这两个问题。剩下的工作就是遍历randomRect并将冲突推送到collRect
class Rectangle {
constructor(topLeftXPos, topLeftYPos, width, length) {
this.topLeftXPos = topLeftXPos;
this.topLeftYPos = topLeftYPos;
this.width = width;
this.length = length;
}
collides(otherRectangle) {
if (this.topLeftXPos === otherRectangle.topLeftXPos) {
return true;
}
else if (this.topLeftYPos === otherRectangle.topLeftYPos) {
return true;
}
else {
return false;
}
}
}
let randomRect = [];
let collRect = [];
function colCheck(n) {
for (let i = 0; i < n; i++) {
//populate randomRect
let newRectangle = new Rectangle(
//top
Math.floor(Math.random() * 10),
//left
Math.floor(Math.random() * 10),
//width
Math.floor(Math.random() * 10),
//length
Math.floor(Math.random() * 10))
randomRect.push(newRectangle);
}
console.log(randomRect)
for( let i = 0; i <n;i++){
for (let j = n-1; j > 0; j--) {
if (randomRect[i].collides(randomRect[j])) {
collRect.push(randomRect[i]);
console.log("Collisaaaion detected")
}
}
}
}
colCheck(1000);
console.log(collRect);https://stackoverflow.com/questions/69173230
复制相似问题