简体   繁体   English

如何在 javascript(p5.js)中相互比较数组(列表)(对象)的所有元素

[英]How to compare all elements of an array(list) (of objects) with each other in javascript (p5.js)

Actually I use p5.js, but I suppose the js built in functions should also work in the same way as in javascript.其实我用的是p5.js,但是我想js内置函数应该也和javascript一样。

Given is a list of dynamically generated objects stored in an array.给定的是存储在数组中的动态生成对象的列表。 The objects have coordinates (x,y), size, and some other attributes.对象具有坐标 (x,y)、大小和一些其他属性。 These objects are moving over the screen according to their attributes (direction, velocity)这些对象根据它们的属性(方向、速度)在屏幕上移动

I want to write a function, where I can check the coordinates of objects, if they collide, they should change directions eg for this I need to compare every element of my array with every other.我想写一个 function,在那里我可以检查对象的坐标,如果它们发生碰撞,它们应该改变方向,例如为此我需要将数组中的每个元素相互比较。

As I have a number of elements I don't know, I iterate with因为我有许多我不知道的元素,所以我迭代

for (let i in array)

then I want to pop the first element, and in the included for each loop compare it with the rest of array.然后我想弹出第一个元素,并在包含的每个循环中将它与数组的 rest 进行比较。

After this loop, I want to unshift this element to the array for doing the same with the whole array.在这个循环之后,我想把这个元素移到数组中,以便对整个数组做同样的事情。

I suppose, that the built in function of pop() doesn't return me this element, because I get an error, which let me think, that the objects of this array are changed with something else.我想,pop() 的内置 function 没有返回这个元素,因为我得到一个错误,这让我想,这个数组的对象被其他东西改变了。

How can I fix that?我该如何解决?

Here is my code of this function:这是我的这个 function 的代码:

function checkCollisions() {

  for (let i in array_of_objects) {
    let element = array_of_objects.pop()
    for (let j in array_of_objects) {
      if (comparison_of_some_attributes_between(element, array_of_objects[j])) {
      some_changes_on_attributes_of(element, array_of_objects[j])
      }
      array_of_objects.unshift(element)
    }
  }

You are using a for each loop, which stores objects, not indexes in the variables ( i , j ).您正在使用 for each 循环,它存储对象,而不是变量( ij )中的索引。 Therefore, you should just use j instead of array_of_objects[j]因此,您应该只使用j而不是array_of_objects[j]

However, most importantly, you should put然而,最重要的是,你应该把

array_of_objects.unshift(element)

outside of the second for loop (move it 2 lines down).第二个 for 循环之外(向下移动 2 行)。 Otherwise, you will unshift it multiple times, where it should only happen once.否则,您将多次取消移动它,而它应该只发生一次。

Also, (and I am not sure this is actually the same in your original code), you are missing a closing curly bracket.此外,(我不确定这在您的原始代码中实际上是否相同),您缺少一个右大括号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM