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

js 类型转换

作者:堕魂灭天   发布日期:2026-02-11   浏览:49

// JavaScript 类型转换示例

// 1. 字符串转数字
let str = "123";
let num = Number(str); // 使用 Number 函数进行转换
console.log(typeof num); // 输出: number

// 2. 数字转字符串
let num2 = 456;
let str2 = num2.toString(); // 使用 toString 方法进行转换
console.log(typeof str2); // 输出: string

// 3. 布尔值转字符串
let bool = true;
let str3 = String(bool); // 使用 String 函数进行转换
console.log(typeof str3); // 输出: string

// 4. undefined 和 null 转数字
let undefinedValue = undefined;
let nullValue = null;
console.log(Number(undefinedValue)); // 输出: NaN (Not a Number)
console.log(Number(nullValue)); // 输出: 0

// 5. 自动类型转换
let result = "10" + 5; // 字符串和数字相加时,数字会被自动转换为字符串
console.log(result); // 输出: "105"

let result2 = "10" - 5; // 减法运算时,字符串会被自动转换为数字
console.log(result2); // 输出: 5

// 6. Boolean 类型转换
let value = "";
console.log(Boolean(value)); // 输出: false,因为空字符串是 falsy 值

value = "hello";
console.log(Boolean(value)); // 输出: true,非空字符串是 truthy 值

上一篇:js 大小写转换

下一篇:js 时间格式转换

大家都在看

js 数组打乱顺序

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js 数组连接

js json数组

js 数组复制

js 复制数组

js 数组拷贝

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

Laravel 中文站