我有一些计算器的代码,如果有结果,我想在结果上加一个%。
当前代码是
var margins = num4.split(" ");
var topMarg = GetIntOrEmpty(margins[0]),
rightMarg = GetIntOrEmpty(margins[1]),
bottomMarg = GetIntOrEmpty(margins[2]),
leftMarg = GetIntOrEmpty(margins[3]);
console.log(topMarg, rightMarg, bottomMarg, leftMarg);
var shorthand1 = GetIntOrEmpty (topMarg);
shorthand1 += ' %';如果shorthand1为空,我希望它不添加‘%’,并将其保留为空。
有什么想法吗?
发布于 2011-12-30 04:27:29
if (shorthand1 !== '')
shorthand1 += '%';发布于 2011-12-30 04:28:43
使用if语句检查变量是否等于空字符串且不是isNaN
if (shorthand1 !== '' && !isNaN(shorthand1)) {
shorthand1 += ' %';
}上面的代码是根据Šime Vidas留下的评论编辑的,如下所示。
参考文献:
发布于 2011-12-30 04:33:26
您的GetIntorEmpty可以返回'0‘而不是空'’,而不是测试是否为空。
这不需要测试,因为0%与0相同。
OR:
如果您必须测试一个数字,并且该数字需要大于0,那么另一种选择是:
if(shorthand >== 1) shorthand += '%';该'>== 1‘只会对一个数字(大于0)返回true。例如,它将在字符串'2‘上返回false。
https://stackoverflow.com/questions/8672986
复制相似问题