如果var不是一个NaN(所以它是一个数字),则在jquery中将%添加到它
我有一些计算器的代码,现在如果有结果,我想在结果中加一个% 当前代码为如果var不是一个NaN(所以它是一个数字),则在jquery中将%添加到它,jquery,calculator,nan,Jquery,Calculator,Nan,我有一些计算器的代码,现在如果有结果,我想在结果中加一个% 当前代码为 var margins = num4.split(" "); var topMarg = GetIntOrEmpty(margins[0]), rightMarg = GetIntOrEmpty(margins[1]), bottomMarg = GetIntOrEmpty(margins[2]), leftMarg = GetIntOrEmpty(margin
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为空,我希望它不要将“%”添加到其中,并将其保留为空
有什么想法吗?使用
if
语句检查变量是否等于空字符串,而不是isNaN
:
if (shorthand1 !== '')
shorthand1 += '%';
if (shorthand1 !== '' && !isNaN(shorthand1)) {
shorthand1 += ' %';
}
上面的代码是根据下面的注释编辑的
参考资料:
if(shorthand >== 1) shorthand += '%';
“>==1”只会在数字(大于0)上返回true。例如,它会在字符串“2”上返回false。您需要向我们显示
GetIntOrEmpty
GetIntOrEmpty的代码在哪里?您有什么问题?因此,GetIntOrEmpty
返回一个数字或字符串值。在我看来,这不是一个好的设计。为什么不通过返回NaN
而不是''
..使其成为唯一的返回号码。。。这就是NaN
值的作用-表示结果不是有效数字的情况。啊?我没有抓住那一点;哎呀。所以想必:shorthand1!=''代码>?是的。您想使用=代码>仅用于显式启用类型强制的比较(这是-从不)…感谢您的关注…总有一天我会了解我在JavaScript方面真正在做什么…=)