问题
The below VBScript code while trying to run in HP-UFT confused me because the first statement prints True
instead of False
(which does not seem logical), while the second one prints False
(which seems logical)
Code:
print 40 = "40"
a = 40
b = "40"
print a = b
Output:
True
False
回答1:
It's perfectly logical (cough), there is only one data type in VBScript and that is Variant
. However VBScript can handle many different sub types of the Variant
data type.
When you compare
40 = "40"
VBScript is implicitly converting the String
sub type to an Integer
sub type and comparing the result which is the same as performing the following explicit conversion;
40 = CInt("40")
If you already have your variants defined however VBScript only attempts to implicitly convert them if the execution context fits (when it fits is a bit hazy and in some cases a straight up bug - See Ref).
To avoid this use explicit conversions when necessary.
a = CInt(b)
Useful Links
- A: VBScript implicit conversion in IF statement different from variable to literals?
- MSDN Blog - Typing Hard Can Trip You Up (Eric Lippert)
来源:https://stackoverflow.com/questions/40465831/integer-and-string-comparison-conflict-in-vbscript