2

只有当变量不是有效的字符串(长度> 0,而不是未定义)时,我才尝试运行代码块。基于this SO post,我认为我做得对,但是每次都会运行。我在这里做错了什么?

    if (creep.memory.sourceid ||creep.memory.depositLoc||creep.memory.sourceType)
    {
        creep.memory.sourceid = getSourceMinWorkers(creep);
        creep.memory.sourceType='energy';
creep.memory.depositLoc=getClosestDepositLoc(creep.memory.sourceid,creep.memory.sourceType);
        console.log(creep.name," harvesting ",creep.memory.sourceType," at: ",creep.memory.sourceid," depositing at: ",creep.memory.depositLoc);
    }

console.log 的输出:

H1_1  harvesting  energy  at:  81a61f68f5eb4057223b05b2  depositing at:  a7633d25d9058f616ab8a0f3
H1_1  harvesting  energy  at:  1649baad43f736c9fc13d2ad  depositing at:  a7633d25d9058f616ab8a0f3
4

1 回答 1

3

您正在使用 OR ( ||) 运算符进行检查。这意味着如果任何一个条件为真(在字符串的情况下为非空),则条件将运行。

你有这个条件:

if (creep.memory.sourceid || creep.memory.depositLoc || creep.memory.sourceType) {

这意味着如果creep.memory.sourceid设置或creep.memory.depositLoc设置或creep.memory.sourceType设置,它将运行。

我看到您正在使用这一行记录 3 个变量:

console.log(creep.name," harvesting ",creep.memory.sourceType," at: ",creep.memory.sourceid," depositing at: ",creep.memory.depositLoc);

每次运行块时都会记录数据,并且我看到 3 个参数是非空字符串,因此代码按预期工作。

根据您的代码,我认为只有在设置了 2 个参数但没有位置的情况下才运行代码,因此您必须将 OR 运算符切换为 AND ( &&),如果所有 3 个条件都为真,这将通过。此外,您还必须检查该位置是否为空,如下所示:

if (creep.memory.sourceid && !creep.memory.depositLoc && creep.memory.sourceType) {
//    Notice the exclamation ^ up there

这样,如果有源 id 并且如果 DON'T( !) 有存放位置并且如果有源类型,则将运行代码块。注意位置参数前的感叹号。这意味着这是对价值的否定。

于 2017-05-24T17:00:41.053 回答