为数组(VBS)中的现有项分配新值

时间:2015-06-24 10:08:07

标签: arrays vbscript

Option Explicit

dim list
Set list = CreateObject("System.Collections.ArrayList")
list.Add split("Banana;Apple;Pear",";")

WScript.Echo  join(list.item(0), ", ") ' --> Banana, Apple, Pear

WScript.Echo  list.item(0)(0)          ' --> Banana

list.item(0)(0) = "Cherry"
WScript.Echo  list.item(0)(0)          ' --> Banana (Why not Cherry?)

list.item(0)返回一个数组。这就是为什么我能加入它。我需要更改一个数组的值。显而易见的是行不通的。为什么呢?

编辑

我发现如果我这样做就行了

Dim arr 
arr = list.item(0)
arr(0) = "Cherry"
list.item(0) = arr

1 个答案:

答案 0 :(得分:2)

分配本机VBScript阵列副本。证据:

>> Dim a : a = Split("a b c")
>> Dim b : b = a
>> b(0) = "A"
>> WScript.Echo Join(a)
>> WScript.Echo Join(b)
>>
a b c
A b c

Split()返回一个VBScript数组。您可以将其分配给列表(0),但这会给列表(0)一个副本。证据:

>> Dim list : Set list = CreateObject("System.Collections.ArrayList")
>> Dim a    : a        = Split("a b c")
>> list.Add a
>> a(0) = "A"
>> WScript.Echo Join(a)
>> WScript.Echo Join(list(0))
>>
A b c
a b c

你的表达式list.item(0) - 或者用较少的烦恼:list(0) - 在陈述中

list.item(0)(0) = "Cherry"

是指列表中数组的副本,分配" Cherry"它的第一个元素不会改变原作'在列表中。证据:你的代码。

你能做什么?

(1)从列表(0)获取副本,更改副本,将(完整)副本分配给列表(0):

>> Dim list : Set list = CreateObject("System.Collections.ArrayList")
>> Dim a    : a        = Split("a b c")
>> list.Add a
>> Dim b    : b        = list(0)
>> b(0) = "Cherry"
>> list(0) = b
>> WScript.Echo Join(list(0))
>>
Cherry b c

(2)避免使用VBScript数组,使用ArrayLists(或字典,或任何 not 在assign上复制的集合):

>> Dim list1 : Set list1 = CreateObject("System.Collections.ArrayList")
>> Dim list2 : Set list2 = CreateObject("System.Collections.ArrayList")
>> list2.Add "Banana"
>> list2.Add "Apple"
>> list1.Add list2
>> WScript.Echo Join(list1(0).ToArray())
>> list1(0)(0) = "Cherry"
>> WScript.Echo Join(list1(0).ToArray())
>>
Banana Apple
Cherry Apple