【问题标题】:How to iterate structures properly如何正确迭代结构
【发布时间】:2015-09-05 16:06:24
【问题描述】:

我想迭代找到的结构,但我不知道哪种方式最适合。

我试过这个:

for (var ext in creep.room.find(FIND_MY_STRUCTURES, {filter: { structureType: STRUCTURE_EXTENSION }})){
    console.log(ext.energy);
}

但它不起作用。

所以现在我正在使用一种可行的方法,但它看起来很丑:

for(var i = 0; i < creep.room.find(FIND_MY_STRUCTURES, {filter: { structureType: STRUCTURE_EXTENSION }}).length; i++) {
    var ext = creep.room.find(FIND_MY_STRUCTURES, {filter: { structureType: STRUCTURE_EXTENSION }})[i];
    console.log(ext.energy);
}

我不确定,也许这是一个与js有关的问题。我是 js 的新手。您能就此提出建议吗?

【问题讨论】:

    标签: javascript screeps


    【解决方案1】:

    ext 包含键,而不是结果的值。

    所以我所做的就是将结果移出循环并放入一个名为results 的变量中。这样,我就有一个变量可以在循环中引用。

    所以发生了什么,因为您的代码中的ext 正在存储密钥,这是一个字符串类型的值。它从字符串对象返回结果,您正在执行类似"key".energy 的操作,并返回值undefined,因为字符串对象没有这样的键。

    所以下面是应该工作的代码:

    var results = creep.room.find(FIND_MY_STRUCTURES, {filter: { structureType: STRUCTURE_EXTENSION }});
    for (var ext in results){
        console.log(results[ext].energy);
    }
    

    【讨论】:

    • 另外,可以使用 Game.structures 迭代自己的结构。它可能比使用函数标记为平均 CPU 的 room.find() 更快。
    • 嗯..我想深入研究这些东西......即使迭代 Game.structures 是一个较小的列表,扩展速率是线性的并且代码执行得非常快。此外,我对这些事情的了解越多,我实际上越喜欢 a) 使用您自己的代码或 b) 需要更好的 screeps api。
    【解决方案2】:

    别忘了你也可以使用Array.forEach函数和箭头函数表示法!

    creep.room.find(FIND_MY_STRUCTURES, { filter: { structureType: STRUCTURE_EXTENSION } })
        .forEach((ext) => { console.log(ext.energy); });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-19
      • 2013-09-25
      • 2018-05-27
      • 2019-11-02
      • 2017-03-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多