JavaScript 假值示例详解

JavaScript 假值有 :false、0、''、null、undefined、NaN

javascript 复制代码
// false- 布尔值假
if (false) {
        console.log("这行永远不会执行");
    } else {
        console.log("false 是假值,所以执行这里");
    }
    // 输出: "false 是假值,所以执行这里"

    // 0 值
    if (0) {
        console.log("这行永远不会执行");
    } else {
        console.log("0 是假值");
    }
    // 输出: "0 是假值"

    // 1. 空字符串
    if ('') {
        console.log("这行永远不会执行");
    } else {
        console.log("空字符串是假值");
    }
    // 输出: "空字符串是假值"

    // 1. 直接使用
    if (null) {
        console.log("这行永远不会执行");
    } else {
        console.log("null 是假值");
    }
    // 输出: "null 是假值"


    // 未初始化的变量
    let declaredButUndefined;
    if (declaredButUndefined) {
        console.log("这行永远不会执行");
    } else {
        console.log("undefined 是假值");
    }
    // 输出: "undefined 是假值"

    // NaN- 非数字
    if (NaN) {
        console.log("这行永远不会执行");
    } else {
        console.log("NaN 是假值");
    }
    // 输出: "NaN 是假值"

	// 3. 假值在实际应用中的处理
	function processUserInput(input) {
	    // 处理各种假值情况
	    if (!input) {
	        return "输入无效";
	    }
	    return `处理结果: ${input}`;
	}

    //null == undefined
    console.log(`null == undefined 值为:`);
    console.log(null == undefined); // 输出 true

注意 几个 "假值" 之间的比较,如下:

javascript 复制代码
// 使用双等号比较
console.log("\n双等号比较 (==):");
console.log(false == 0);        // true
console.log(false == '');       // true
console.log(0 == '');           // true
console.log(null == undefined); // true
console.log(NaN == NaN);        // false (特殊!)

// 使用三等号比较
console.log("\n三等号比较 (===):");
console.log(false === 0);        // false
console.log(false === '');       // false
console.log(0 === '');           // false
console.log(null === undefined); // false
console.log(NaN === NaN);        // false

有没有一种方法,只检查null与undefined了?

?? 是 JavaScript 中的逻辑运算符,用于检查左侧表达式是否为 null或 undefined,如果是,则返回右侧的值;否则返回左侧的值。

javascript 复制代码
// 只有当左侧是 null 或 undefined 时,才返回右侧
null ?? '默认值'       // 返回 '默认值'
undefined ?? '默认值'  // 返回 '默认值'

// 其他任何值(包括假值)都返回左侧
0 ?? 100              // 返回 0
false ?? true         // 返回 false
'' ?? '空字符串'      // 返回 ''
NaN ?? 10            // 返回 NaN
[] ?? '数组'         // 返回 []
{} ?? '对象'         // 返回 {}
相关推荐
小糖学代码1 天前
LLM系列:1.python入门:15.JSON 数据处理与操作
开发语言·python·json·aigc
空中海1 天前
第七章:vue工程化与构建工具
前端·javascript·vue.js
handler011 天前
从源码到二进制:深度拆解 Linux 下 C 程序的编译与链接全流程
linux·c语言·开发语言·c++·笔记·学习
zhensherlock1 天前
Protocol Launcher 系列:Trello 看板管理的协议自动化
前端·javascript·typescript·node.js·自动化·github·js
zhuà!1 天前
element的el-form提交校验没反应问题
前端·elementui
小白学大数据1 天前
现代Python爬虫开发范式:基于Asyncio的高可用架构实战
开发语言·爬虫·python·架构
龙猫里的小梅啊1 天前
CSS(一)CSS基础语法与样式引入
前端·css
小码哥_常1 天前
从0到1,开启Android音视频开发之旅
前端
渔舟小调1 天前
P19 | 前端加密通信层 pikachuNetwork.js 完整实现
开发语言·前端·javascript
不爱吃炸鸡柳1 天前
数据结构精讲:树 → 二叉树 → 堆 从入门到实战
开发语言·数据结构