【问题标题】:How can i splice current index in a foreach?如何在 foreach 中拼接当前索引?
【发布时间】:2013-05-28 21:58:12
【问题描述】:

我有这个 foreach 循环来检查碰撞,我希望在发生碰撞时删除平台(movieclip)。到目前为止,我想出了这个:

if (mcContent.mcPlayer.y + mcContent.mcPlayer.height > platformCloud.y) 
                                {
                                    mcContent.mcPlayer.y = platformCloud.y - mcContent.mcPlayer.height - 1;
                                    jump();
                                    mcContent.removeChild(platformCloud);
                                    //platformsCloud.splice(platformCloud);
                                }

这样做的目的是删除影片剪辑(到目前为止还不错)但没有拼接,当循环再次通过数组运行时,它仍然存在。因此,注释掉的拼接存在 1 个小问题,它从数组中删除了所有的影片剪辑。

如何只拼接当前正在检查的索引?

【问题讨论】:

  • 为什么要保留对已删除对象的引用?将它们与“活动”对象放在同一位置是否有意义?
  • 我不是这就是为什么我要使用 removeChild 删除它们,然后将它们从数组中取出,这样它们就不会被再次检查。至少这就是我试图用这段代码实现的目标。
  • forEach 循环中? Don't!

标签: arrays actionscript-3 flash-cs5 splice


【解决方案1】:

.splice() 接受起始索引和要删除的项目数量,而不是您要从数组中删除的对象。

参数

startIndex:int — 一个整数,它指定数组中插入或删除开始的元素的索引。您可以使用负整数来指定相对于数组末尾的位置(例如,-1 是数组的最后一个元素)。

deleteCount:uint — 一个整数,指定要删除的元素数。此数字包括 startIndex 参数中指定的元素。如果您没有为 deleteCount 参数指定值,则该方法将删除数组中从 startIndex 元素到最后一个元素的所有值。如果值为 0,则不删除任何元素。

你想这样做:

var index:int = platformsCloud.indexOf(platformCloud);
platformsCloud.splice(index, 1);

【讨论】:

  • 现在正在工作,但我回家后肯定会研究它,这似乎是正确的用途,我正在单独学习 as3,这就是为什么我不正确地使用它的原因,也许。
【解决方案2】:

为什么不直接创建一个new 数组来保留项目?使用Array.push 添加新项目。这可能实际上比修改现有数组更有效。它也不需要跟踪索引(需要使用Array.splice)。

示例代码:

var keptPlatforms = [];
// do stuff
if (mcContent.mcPlayer.y + mcContent.mcPlayer.height > platformCloud.y) 
{
    mcContent.mcPlayer.y = platformCloud.y - mcContent.mcPlayer.height - 1;
    jump();
    mcContent.removeChild(platformCloud);
} else {
    keptPlatforms.push(platformCloud);
}
// later, after this cycle, use the new Array
platformClouds = keptPlatforms;

现在,platformsCloud.splice(platformCloud) 删除 所有 项的原因是因为第一个参数被强制转换为整数,因此它等效于 platformsCloud.splice(0) 表示“将第 0 个索引项删除到末尾的数组”。而且,这确实清除了数组。

要使用Array.splice,您必须执行以下操作:

// inside a loop this approach may lead to O(n^2) performance
var i = platformClouds.indexOf(platformCloud);
if (i >= 0) {
    platformClouds.splice(i, 1); // remove 1 item at the i'th index
}

【讨论】:

  • 但是我必须检查 keepPlatforms 而不是 platformClouds 对吗?
  • @BrunoCharters 修正了使用 Array.splice 时的错字 - 使用 Array.splice remove 项并创建一个新数组,其中仅包含要 keep 是两种不同的方法。我建议不要在这里使用 Array.splice。但是,是的,如果您需要在一个周期内多次重新检查同一个平台(应该考虑一下,因为这听起来效率低下),那么您只需要查看当前项目。
  • 您还可以使用 Array 类的过滤器功能将列表过滤到具有对阶段和/或父级的有效引用的对象。
猜你喜欢
  • 1970-01-01
  • 2010-11-29
  • 2011-06-02
  • 1970-01-01
  • 2016-08-21
  • 2014-08-03
  • 2011-10-12
  • 1970-01-01
  • 2016-09-25
相关资源
最近更新 更多