1

I'm new to VBScript and rather perplexed as to why the following code works:

set Adapters = GetObject("winmgmts:").InstancesOf("Win32_NetworkAdapterConfiguration")

for each Nic in Adapters
    if Nic.IPEnabled then
        MsgBox "IP Address: " & Nic.IPAddress(asdf), 4160, "IP Address"
    end if
next

When the variable asdf is undefined, it works. If I define asdf to an invalid index (e.g. -1 or 4), I get an invalid index error.

I thought: Perhaps undefined variables default to 0 in VBS? Nope, I tried to print it and nothing is written.

Where is the functionality of passing an undefined variable as an array index returning the first item in the array documented? What are some other, similar oddities I may run into while programming in VBScript?

Edit: Some things I've discovered:

  • Undefined variables are equal to Empty by default in VBScript
  • Empty = 0 is true
  • Nic.IPAddress(Empty) also returns the first element of the array
  • MsgBox 0 will print 0, while MsgBox Empty will print nothing

I'm still having trouble finding any documentation stating that array indexing handles Empty quietly by returning the first element, explaining why it is equivalent to but printed differently from 0, and what other constructs handle Empty parameters (and what they do as a result).

4

2 回答 2

2

未定义的变量是Empty,返回Empty数组的索引也将返回0索引。

IPAddress数组中,有两个索引 a0和 a 1

所以这将与您的代码具有相同的效果:
MsgBox "IP Address: " & Nic.IPAddress(0), 4160, "IP Address"
并且
MsgBox "IP Address: " & Nic.IPAddress(Empty), 4160, "IP Address"

这将为您提供 IPv6 地址:
MsgBox "IP Address: " & Nic.IPAddress(1), 4160, "IP Address"

此外,这将返回数组的两个索引:
WScript.Echo Join(Nic.IPAddress,",")

另外,考虑这个例子,
arr = Array("first","second","third")
WScript.Echo arr(Empty)

这里的输出将是first

有关 VBScript 数据类型,请参阅此帖子:
“空:变量未初始化。数值变量的值为 0 或字符串变量的零长度字符串 ("")
。` http://msdn.microsoft.com/en-us/库/9e7a57cf(v=vs.84).aspx

于 2013-11-08T16:21:49.047 回答
0

非常感谢 Langstrom 提供了这一点:“空:变量未初始化。数值变量的值为 0,字符串变量的值为零长度字符串 ("")。”

空的:

Nic.IPAddress(asdf)将参数视为 int,并且CInt(Empty)等于0数组第一个元素的索引。

MsgBox asdf将参数视为字符串,并CStr(Empty)返回一个空字符串。

任何需要整数且为有效值的函数的工作方式与使用参数调用时传递的函数0完全相同。0Empty

比较时Empty = 0,Empty被视为整数,因为它与整数进行比较,因此表达式为真。

比较时Empty = "0"Empty被视为字符串,因此表达式为假。因此,Empty = ""是真的。

无效的:

另外,值得一提的Null是,它不等于任何东西,包括它自己。Null = Null是假的。

于 2013-11-08T16:45:01.687 回答