【问题标题】:array.slice(start, end) in vbscript?vbscript 中的array.slice(开始,结束)?
【发布时间】:2019-07-25 13:29:31
【问题描述】:

有人喜欢 vbscript 中标准(例如 jscript、javascript)array.slice(start,end) 函数的实现吗?

它似乎经常被忽略(无论如何在 vbscript 程序员中),分享一个好的实现会有所帮助。如果没有出现,我想我将不得不回答我自己的问题并写一些东西。

【问题讨论】:

    标签: vbscript slice


    【解决方案1】:

    为了完整起见,这可能是一个更好的版本:

    Function Slice (aInput, Byval aStart, Byval aEnd)
        If IsArray(aInput) Then
            Dim i
            Dim intStep
            Dim arrReturn
            If aStart < 0 Then
                aStart = aStart + Ubound(aInput) + 1
            End If
            If aEnd < 0 Then
                aEnd = aEnd + Ubound(aInput) + 1
            End If
            Redim arrReturn(Abs(aStart - aEnd))
            If aStart > aEnd Then
                intStep = -1
            Else
                intStep = 1
            End If
            For i = aStart To aEnd Step intStep
                If Isobject(aInput(i)) Then
                    Set arrReturn(Abs(i-aStart)) = aInput(i)
                Else
                    arrReturn(Abs(i-aStart)) = aInput(i)
                End If
            Next
            Slice = arrReturn
        Else
            Slice = Null
        End If
    End Function
    

    这避免了上一个答案的一些问题:

    1. 不考虑数组中的对象
    2. 允许负开始和结束值;他们从最后倒数
    3. 如果 start 高于 end 则给出一个反向数组子集
    4. 不需要(昂贵的)redim 保留,因为数组是空的
    5. 如果输入不是数组,则返回定义的结果 (Null)
    6. 使用内置函数IsArray,而不是对输入进行字符串操作/比较

    【讨论】:

      【解决方案2】:

      这是我过去用过的一个:

      Function Slice(arr, starting, ending)
      
          Dim out_array
      
          If Right(TypeName(arr), 2) = "()" Then
              out_array = Array()
              ReDim Preserve out_array(ending - starting)
              For index = starting To ending
                  out_array(index - starting) = arr(index)
              Next
          Else
              Exit Function
          End If
      
          Slice = out_array
      
      End Function
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-26
        • 2021-12-23
        • 2021-04-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多