仅当变量不是有效字符串(长度> 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
最佳答案
您正在使用 OR (||
) 运算符进行检查。这意味着如果任一条件为 true(如果是字符串则非空),则条件将运行。
你有这个条件:
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);
每次运行该 block 时都会记录数据,并且我看到 3 个参数都是非空字符串,因此代码按预期工作。
根据您的代码,我认为只有在设置了 2 个参数但没有位置的情况下才运行代码,因此您必须将 OR 运算符切换为 AND (&&
),这如果所有 3 个条件都为真,则通过。此外,您还必须检查该位置是否为空,如下所示:
if (creep.memory.sourceid && !creep.memory.depositLoc && creep.memory.sourceType) {
// Notice the exclamation ^ up there
这样,如果有源 ID 并且 DON'T(!
) 有存款位置并且有源类型,则代码块将运行。请注意位置参数之前的感叹号。这意味着这是该值的负数。
关于javascript - 仅在未设置字符串值时运行,每次都运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44164384/