Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js string转boolean

作者:⒈种依靠゛ζ   发布日期:2025-12-17   浏览:95

// 将字符串转换为布尔值

// 方法1: 使用 !! 操作符
function stringToBoolean(str) {
    return !!str;
}

// 解释: !! 是双重否定操作符,它会将任何值先转换为布尔值,然后再取反两次,最终得到原始值对应的布尔值。
// 注意: 这种方法下,空字符串 "" 会被转换为 false,非空字符串会被转换为 true。

console.log(stringToBoolean(""));      // 输出: false
console.log(stringToBoolean("hello")); // 输出: true


// 方法2: 使用 Boolean 构造函数
function stringToBooleanUsingBoolean(str) {
    return Boolean(str);
}

// 解释: Boolean 构造函数可以直接将传入的值转换为布尔值。
// 注意: 和 !! 操作符一样,空字符串 "" 会被转换为 false,非空字符串会被转换为 true。

console.log(stringToBooleanUsingBoolean(""));      // 输出: false
console.log(stringToBooleanUsingBoolean("world")); // 输出: true

上一篇:js 字母小写

下一篇:js do while

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象数组合并

js 对象转数组

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站