跳到主要内容

Boolean 布尔类

Boolean 是 Alia 的内置布尔类,用于表示逻辑值 true 和 false。

创建布尔值​

字面量​

const bool1 = true
const bool2 = false

构造器形式​

const bool3 = new Boolean [true]
const bool4 = Boolean[true]
const bool5 = Boolean[1] ~ 输出 true
const bool6 = Boolean[0] ~ 输出 false

实例方法​

toString​

该方法返回布尔值对应的字符串,签名为 alias -> String。

const bool = true
print call bool.toString ~ 输出 'true'

valueOf​

该方法返回布尔值的原始值,签名为 alias -> Boolean。

const bool = true
print call bool.valueOf ~ 输出 true

toNumber​

该方法返回布尔值对应的数值,签名为 alias -> Number。true 对应 1,false 对应 0。

const bool = true
print call bool.toNumber ~ 输出 1
const no = false
print call no.toNumber ~ 输出 0

toArray​

该方法返回包含该布尔值的单元素数组,签名为 alias -> Array。

const bool = true
print call bool.toArray ~ 输出 Array [Boolean true]

toCode​

该方法返回布尔值的代码形式字符串,签名为 alias -> String。

const bool = true
print call bool.toCode ~ 输出 'true'

toDescription​

该方法返回布尔值的描述字符串,签名为 alias -> String。

const bool = true
print call bool.toDescription ~ 输出 'Boolean true'

逻辑运算​

逻辑与 (&)​

const a = true
const b = false
print a & b ~ 输出 false

逻辑或 (|)​

const a = true
const b = false
print a | b ~ 输出 true

逻辑非 (!)​

const a = true
print !a ~ 输出 false

条件判断​

布尔值与条件判断对应:

const age = 18
const isAdult = age >= 18

if isAdult {
print '成年人'
} else {
print '未成年人'
}

三元运算符​

const age = 18
const status = age >= 18 ? '成年人' : '未成年人'
print status

示例代码​

const bool1 = true
const bool2 = false

print '布尔值 1: ' .. (call bool1.toString)
print '布尔值 2: ' .. (call bool2.toString)

print 'true & false: ' .. (true & false)
print 'true | false: ' .. (true | false)
print '!true: ' .. (!true)

const a = 10
const b = 5
const isGreater = a > b
print 'a > b: ' .. (call isGreater.toString)

const age = 18
const isAdult = age >= 18

if isAdult {
print '成年人'
} else {
print '未成年人'
}

const score = 85
const grade = score >= 60 ? '及格' : '不及格'
print '成绩等级: ' .. grade

const num = 1
const boolFromNum = num as Boolean
print '从数字转换: ' .. (call boolFromNum.toString)

const str = ''
const boolFromStr = Boolean[str]
print '从空字符串转换: ' .. (call boolFromStr.toString)

下一步​