1

vbscript中下面的值是什么

1)x=1+"1" 2)x="1"+"1" 3)x=1+"mulla" 注意:在以上三种情况下,我使用第一个变量作为字符串或整数,第二个变量一如既往地作为字符串。

案例1:作为数值,在运行过程中自动转换为数值

enter code here
y=inputbox("Enter a numeric value","") Rem I am using 1 as input
x=1
msgbox x+y Rem value is 2
msgbox x*y Rem value is 1

案例2:作为字符串,在操作过程中不转换为数字失败

enter code here
y=inputbox("Enter a numeric value","") Rem I am using 1 as input
x=1
if y= x then
    msgbox "pass"
else
    msgbox "fail"
end if

案例3:作为一个字符串,在它通过的操作过程中显式转换为数字

enter code here
y=inputbox("Enter a numeric value","") Rem I am using 1 as input
x=1
if Cint(y) = x then
    msgbox "pass"
else
    msgbox "fail"
end if

我需要不同行为的逻辑原因。但在其他语言中,它是直截了当的,并且会按预期工作

4

2 回答 2

5

参考: 加法运算符 (+) (VBScript)

虽然您也可以使用 + 运算符连接两个字符串,但您应该使用 & 运算符进行连接以消除歧义。当您使用 + 运算符时,您可能无法确定是否会发生加法或字符串连接。表达式的类型通过以下方式确定 + 运算符的行为:

如果两个表达式都是数字,则结果是两个数字相加。

如果两个表达式都是字符串,则结果是两个字符串的串联。

如果一个表达式是数字,另一个是字符串,Error: type mismatch则将抛出 an。

使用混合数据类型时,最好使用类型转换函数将变量转换为通用数据类型。

于 2016-07-20T09:19:24.343 回答
2

I agree with most of what @thomas-inzina has said but the OP has asked for a more detailed explanation so here goes.

As @thomas-inzina point's out using + is dangerous when working with strings and can lead to ambiguity depending on how you combine different values.

VBScript is a scripting language and unlike it's big brothers (VB, VBA and VB.Net) it's typeless only (some debate about VB and VBA also being able to be typeless but that's another topic entirely) which means it uses one data type known as Variant. Variant can infer other data types such as Integer, String, DateTime etc which is where the ambiguity can arise.

This means that you can get some unexpected behaviour when using + instead of & as + is not only a concatenation operator when being used with strings but also a addition operator when working with numeric data types.

Dim x: x = 1
Dim y: y = "1"

WScript.Echo x + y

Output:

2
Dim x: x = "1"
Dim y: y = "1"

WScript.Echo x + y

Output:

11
Dim x: x = 1
Dim y: y = 1

WScript.Echo x + y

Output:

2
Dim x: x = 1
Dim y: y = "a"

WScript.Echo x + y

Output:

Microsoft VBScript runtime error (4, 5) : Type mismatch: '[string: "a"]'
于 2016-07-20T13:15:09.643 回答