简体   繁体   English

访问数组中的所有变量

[英]Access all variables in an array

I'm sure this is a simple question but I'm asking it anyways. 我敢肯定这是一个简单的问题,但无论如何我都在问。 Basically I'm trying to do the following in javascript (no jquery) with less code: 基本上,我正在尝试使用更少的代码在javascript(无jquery)中执行以下操作:

var Ground = [];

function gameLoop()
{
    Gravity += 0.2

    if(Ground[0].isCollided(Player))
    {
        Player.dy = 0;
        Gravity = 0;
    }
    if(Ground[1].isCollided(Player))
    {
        Player.dy = 0;
        Gravity = 0;
    }
    if(Ground[2].isCollided(Player))
    {
        Player.dy = 0;
        Gravity = 0;
    }

    Player.dy = Gravity;
}

I've simplified the code extremely from the code in my game I'm making using javascript and the html5 canvas. 从我使用javascript和html5 canvas制作的游戏代码中,我已经极大地简化了代码。 What you see is my Ground mechanic as it stands. 您所看到的是我的地面机械师。 When the player collides with the Ground Block, the Player's .dy value will no longer change along with the Gravity. 当玩家与地面障碍物碰撞时,玩家的.dy值将不再随着重力而变化。

What you saw above is how I would normally do it however this can take up a large amount of space if I have 50 FallingM variables. 上面您看到的是我通常会执行的操作,但是如果我有50个FallingM变量,这可能会占用大量空间。 Is it possible to do something like: 是否可以做类似的事情:

if(Ground[i].isCollided(Player))
{
    Player.dy = 0;
    Gravity = 0;
}

So that the function will still run no matter how many Ground variables I add? 这样,无论我添加多少地面变量,该函数仍将运行? Thanks ahead of time! 提前谢谢!

You should use a loop: 您应该使用循环:

for(var x of Ground) {
   if(x.isCollided(Player)) {
      Player.dy = 0;
      Gravity = 0;
      break;
   }
}

Remember, a Jedi's strength flows from the loops. 请记住,绝地的力量来自循环。 But beware. 但是要当心。 Map , reduce , some . 映射减少 一些 The dark side are they. 黑暗的一面是他们。 Once you start down the dark path, forever will it dominate your destiny. 一旦您走上了黑暗的道路,它将永远统治您的命运。

if (grounds.some(ground => ground.isCollided(player))) {
  player.dy = 0;
  gravity = 0;
}

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

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