经典 asp:通过引用调用函数不适用于数组
我有一个数组,我通过引用传递给函数以对其进行排序。然而,似乎数组是通过val传递的。任何人都可以解决什么问题吗? (也接受排序解决方法)
1) 下面的脚本通过引用将数组传递给排序函数。
2) Sort 函数输出排序后的数组值。
3) 脚本输出排序后的数组值。然而它们没有排序。
脚本输出:
300,200,100,,
100,200,300,
'declare variables
mitta(1) = 1
mitta(2) = 2
mitta(3) = 3
sort(mitta) ' see the function below
' show variables
For i = 1 To 3
response.write mitta(i) & ","
next
' sort function
function sort(byref a)
dim num,i,j,temp
num = ubound(a)+1
For i = 0 To num - 1
For j = i + 1 To num - 1
If a(i) < a(j) Then
temp = a(i)
a(i) = a(j)
a(j) = temp
End If
Next
Next
' show sorted variables
For i = 0 To num - 1
response.write a(i) & ","
a(i) = 0
next
end function
I have an array witch I pass to a function by reference to sort it. However, seems like the array is passed byval. Can anyone solve what's the problem? (Also sort workarounds accepted)
1) The script below passes an array by-reference to the sort function.
2) Sort function outputs the sorted array values.
3) The script outputs the sorted array values. However they are not sorted.
The script outputs:
300,200,100,,
100,200,300,
'declare variables
mitta(1) = 1
mitta(2) = 2
mitta(3) = 3
sort(mitta) ' see the function below
' show variables
For i = 1 To 3
response.write mitta(i) & ","
next
' sort function
function sort(byref a)
dim num,i,j,temp
num = ubound(a)+1
For i = 0 To num - 1
For j = i + 1 To num - 1
If a(i) < a(j) Then
temp = a(i)
a(i) = a(j)
a(j) = temp
End If
Next
Next
' show sorted variables
For i = 0 To num - 1
response.write a(i) & ","
a(i) = 0
next
end function
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通过在函数调用
sort(mitta)
中将mitta
括在括号中,您实际上是按值传递它,尽管有函数声明。来自 http://blogs.msdn.com/b/ericlippert/archive/2003 /09/15/52996.aspx:另请参阅 MSDN 参考以了解 ByRef 和 ByVal 参数。相反,您应该使用以下方式调用
sort
:或:
By wrapping
mitta
in parentheses in the function callsort(mitta)
, you're actually passing it by value, despite the function declaration. From http://blogs.msdn.com/b/ericlippert/archive/2003/09/15/52996.aspx:See also the MSDN reference for ByRef and ByVal Parameters. Instead, you should call
sort
either with:or:
就是这样,只需添加关键字
call
即可。完整参考可在此处获取 。顺便说一句,您的代码有问题。数组是从 0 开始的。
That's it, just add the keyword
call
. Complete reference is available here.BTW, your code has problems. The arrays are 0 based.
当您将
对象
作为参数传递时,您将指针
传递给对象
,而不是对象本身(这适用于我所知道的所有语言)。因此,传递
ByVal
还是ByRef
并不重要,因为根据定义,您始终传递一个指针
(对对象的引用)When you pass an
object
as parameter, you are passing apointer
to theobject
, not theobject
itself (this apply to all languages I know). So it does not matter if you pass itByVal
orByRef
, because by definition you are always passing apointer
(a reference to the object)