VBScript字典存在方法始终返回True

use*_*001 7 vbscript dictionary exists

我究竟做错了什么?从我的测试中,objDic.exists永远不会给出错误!

    dim objDic

    set objDic = createobject("scripting.dictionary")

    objDic.add "test","I have not been deleted"

    wscript.echo objDic.item("test") 'Displays -- I have not been deleted

    objDic.remove "test"

    wscript.echo """" & objDic.item("test") & """" 'Displays -- ""

    if objDic.exists("test") then wscript.echo """" & objDic.item("test") & """" 'Displays -- ""
Run Code Online (Sandbox Code Playgroud)

HK1*_*HK1 12

就像我所知,一个字典对象密钥只是通过引用它来创建,就好像它确实存在一样.

wscript.echo objDic.Item("test") 'Creates the key whether it exists or not
wscript.echo objDic.Exists("test") 'Will now return true
Run Code Online (Sandbox Code Playgroud)

这里有一些代码可以用来证明/测试我的理论.我通常使用MsgBox而不是WScript.Echo,正如您将在我的代码中看到的那样.

dim objDic, brk
brk = vbcrlf & vbcrlf
set objDic = createobject("scripting.dictionary")
objDic.add "test","I have not been deleted"
wscript.echo "objDic.Exists(""test""): " & brk & objDic.item("test")
WScript.Echo "Now going to Remove the key named: test"
objDic.remove "test"
MsgBox "objDic.Exists(""test""): " & brk & objDic.Exists("test") 'Returns False
wscript.echo "objDic.item(""test""): " & brk & objDic.item("test") 'Shows Blank, Creates the key again with a blank value
wscript.echo "objDic.item(""NeverAdded""): " & brk & objDic.item("NeverAdded") 'Also shows blank, does not return an error
MsgBox "objDic.Exists(""test""): " & brk & objDic.Exists("test") 'Returns True
Run Code Online (Sandbox Code Playgroud)

  • 完全正确.这是[官方文档](http://msdn.microsoft.com/en-us/library/84k9x471%28VS.84%29.aspx),其中提到"如果*key*在尝试返回时未找到现有项目,新*键*被创建,其相应项目为空." (2认同)
  • 在重新回答此问题时,由新答案提示,我同样困惑于密钥的创建(如果它不存在)如何有帮助,就像我上次查看此问题时一样。谁能解释这背后的原因?我只能假设这植根于comp。科学 关于字典对象的理论? (2认同)
  • @ user66001作为一个实用的程序员,我更少担心为什么像这样的设计是这样的,并且更担心记住这些怪癖. (2认同)