VBScript 程式設計教學:運算子 (Operator)

PUBLISHED ON AUG 19, 2018 — PROGRAMMING
FacebookTwitter LinkedIn LINE Skype EverNote GMail Yahoo Email

    VBScript 中有三種運算子:

    • 代數運算子
    • 關係連算子
    • 邏輯運算子

    代數運算子

    包括以下功能:

    • 相加 +
    • 相減 -
    • 相乘 *
    • 相除 / (得小數)
    • 相除 \ (得整數)
    • 取餘數 Mod
    • 指數 ^

    以下是實例:

    ' Arithmetic operators
    Assert 3 + 4 = 7, "It should be " & (3 + 4)
    Assert 3 - 4 = -1, "It should be " & (3 - 4)
    Assert 3 * 4 = 12, "It should be " & (3 * 4)
    Assert 3 / 4 = 0.75, "It should be " & (3 / 4)
    Assert 3 \ 4 = 0, "It should be " & (3 \ 4)
    Assert 10 Mod 3 = 1, "It should be " & (10 Mod 3)
    Assert 3 ^ 4 = 81, "It should be " & (3 ^ 4)
    
    ' Home-made assert for VBScript
    Sub Assert( boolExpr, strOnFail )
        If Not boolExpr Then
            Err.Raise vbObjectError + 99999, , strOnFail
        End If
    End Sub
    

    註:VBScript 沒有內建的 assert 語句,使用者要自行製作。

    關係運算子

    包括以下特性:

    • 相等 =
    • 不相等 <>
    • 大於 >
    • 大於或等於 >=
    • 小於 <
    • 小於或等於 <=

    我們用一個簡例來說明如何使用這些運算子:

    ' Relational operators.
    Assert 3 + 4 > 5, "It should be larger"
    Assert 3 + 4 >= 5, "It should be larger"
    Assert 3 + 4 < 10, "It should be smaller"
    Assert 3 + 4 <= 10, "It should be smaller"
    Assert 3 + 4 = 7, "It should be equal"
    Assert 3 + 4 <> 5, "It should not be equal"
    
    ' Home-made assert for VBScript
    Sub Assert( boolExpr, strOnFail )
        If Not boolExpr Then
            Err.Raise vbObjectError + 99999, , strOnFail
        End If
    End Sub
    

    邏輯運算子

    包括以下功能:

    • And
    • Or
    • Not

    以下是實例:

    ' Logic operator - And.
    Assert ((True And True) = True), "It should be true"
    Assert ((True And False) = False), "It should be false"
    Assert ((False And True) = False), "It should be false"
    Assert ((False And False) = False), "It should be false"
    
    ' Logic operator - Or
    Assert ((True Or True) = True), "It should be true"
    Assert ((True Or False) = True), "It should be true"
    Assert ((False Or True) = True), "It should be true"
    Assert ((False Or False) = False), "It should be false"
    
    ' Logic operator - Not
    Assert ((Not True) = False), "It should be false"
    Assert ((Not False) = True), "It should be true"
    
    ' Home-made assert for VBScript
    Sub Assert( boolExpr, strOnFail )
        If Not boolExpr Then
            Err.Raise vbObjectError + 99999, , strOnFail
        End If
    End Sub