if (firstPositionCpc && (firstPosition > 0 && firstPositionCpc <= maxCPC)) {
var newCPC = firstPositionCpc;
} else if (topOfPageCpc && (topOfPageCpc > 0 && topOfPageCpc <= maxCPC)) {
var newCPC = topOfPageCpc;
} else if (firstPageCpc && (firstPageCpc > 0 && firstPageCpc <= maxCPC )) {
var newCPC = firstPageCpc;
} else {
var newCPC = minCPC;
}
这是一些错误的场景
KeywordIdReport :197857118477
campaignName :BP 2015 QC (FR)
maxCPC : 3.00
OldCPC :0.46
firstPositionCpc : --
topOfPageCpc : 0.46
firstPageCpc : 0.05
NewCPC : --
这里NewCPC
需要是一个数字。因此,firstPositionCpc
、topOfPageCpc
和 firstPageCpc
需要存在并且是一个数字。
KeywordIdReport :97483945
campaignName :BP 2015 QC (FR)
maxCPC: 3.00
OldCPC :1.96
firstPositionCpc : 4.28
topOfPageCpc : 1.68
firstPageCpc : 0.85
NewCPC : 4.28
此处,NewCPC
需要低于或等于 maxCPC
。通常,NewCPC
的答案应为 1.68
,而不是 4.28
。
如何修复 if 语句链,以便修复错误的场景?
更新
现在改进后,怎么能说firstPositionCpc
、topOfPageCpc
和firstPageCpc
的类型存在并且需要是数字呢?
最佳答案
Hence, firstPositionCpc, topOfPageCpc and firstPageCpc need to exist and be a number.
鉴于您有 3 个比较,上述内容并没有真正意义,因此我的答案将依赖于您想要 firstPosition > 0
的假设。 .
所以我需要检查值类型是否为数字以及该数字是否在某个范围内,因此采用第一个 if 语句:
if (firstPositionCpc && (firstPosition > 0 && firstPositionCpc <= maxCPC)) {
var newCPC = firstPositionCpc;
}
我会将其更改为以下内容:
if(typeof(firstPositionCpc) == 'number' && firstPositionCpc <= maxCPC && firstPosition > 0){....}
typeof()
读取参数的类型并返回指示值的字符串。
参见此处https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
关于javascript - 改进 if 语句链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47266043/