【JavaScript基础】Null类型详解

在JavaScript中,Null是一个原始数据类型,表示变量被明确赋值为空值或"无值"状态。

1. Null类型主要场景

1)变量初始化

js 复制代码
let user = null;
user = { name: 'cxh', age: 18 };

2)函数返回值

js 复制代码
// 函数找不到结果时返回 null
function findUser(id) {
    const users = [
        { id: 1, name: 'cxh001' },
        { id: 2, name: 'cxh002' }
    ];
    return users.find(user => user.id === id) || null;
}
console.log(findUser(3)); // null

// 操作失败时返回 null
function parseJSON(str) {
    try {
        return JSON.parse(str);
    } catch (error) {
        return null;
    }
}

3)DOM操作

js 复制代码
    // 获取不存在的元素返回 null
    const nonExistentElement = document.getElementById('non-existent');
    console.log(nonExistentElement); // null

    // 移除元素后设置为 null
    let element = document.getElementById('myElement');
    element?.parentNode?.removeChild(element);
    element = null; // 帮助垃圾回收

4)对象属性的清理

js 复制代码
    const app = {
        cache: {},
        config: null
    };
    // 使用缓存后清理
    app.cache.userData = { /* 大量数据 */ };
    // 释放内存
    app.cache.userData = null;

5)函数的可选参数

js 复制代码
    function createUser(name, details = null) {
        return {
            name,
            details
        };
    }
    console.log(createUser('cxh')); // {name: 'cxh', details: null}

6)API 响应处理

js 复制代码
    // 常见于数据库查询结果
    const apiResponse = {
        success: true,
        data: null, // 没有找到数据
        message: 'User not found'
    };
    // 或者
    async function getUserProfile(userId) {
        const response = await fetch(`/api/users/${userId}`);
        const result = await response?.json();
        return result?.data || null; // 有数据返回数据,没有返回 null
    }

7)状态管理

js 复制代码
    class AuthService {
        currentUser = null;
        token = null;

        constructor() {}

        login(userData, authToken) {
            this.currentUser = userData;
            this.token = authToken;
        }

        logout() {
            this.currentUser = null;
            this.token = null;
        }
    }

8)配置和选项

js 复制代码
    function initializeApp(config = {}) {
        const defaults = {
            apiUrl: 'https://api.example.com',
            timeout: 5000,
            retryCount: null, // 不重试
            logger: null // 不记录日志
        };
        return { ...defaults, ...config };
    }

9)未匹配到正则

js 复制代码
    // RegExp.exec() 方法没有匹配
    const regex1 = /hello (\w+)/;
    const str = 'goodbye world';
    console.log(regex1.exec(str)); // null

    // String.match() 没有匹配结果
    const regex2 = /(\d{3})-(\d{3})-(\d{4})/;
    const phone = '没有电话号码';
    console.log(phone.match(regex2)); // null

2. 检测Null的方法

1)严格相等

js 复制代码
    let value = null;
    if (value === null) {
        console.log('Value is null'); // Value is null
    }

2)联合检查Null和Undefined

js 复制代码
    let value;
    if (value == null) {
        console.log('Value is null or undefined'); // Value is null or undefined
    }

3)使用可选链操作符安全访问

js 复制代码
    const userName = user?.profile?.name ?? 'default';

3. Undefined和Null的异同

特性 Undefined Null
类型 独立类型(Undefined) 独立类型(Null)
含义 变量声明但未赋值 表示一个空对象指针
默认值 函数无返回值时的默认返回 需显式赋值
相等性 undefined == null → true undefined === null → false
类型检测 typeof undefined→ 'undefined' typeof null → 'object'
转换为数字 Number(undefined) → NaN Number(null) → 0
转换为布尔值 Boolean(undefined)→ false Boolean(null) → false

相关推荐
2501_920931704 小时前
React Native鸿蒙跨平台采用ScrollView的horizontal属性实现横向滚动实现特色游戏轮播和分类导航
javascript·react native·react.js·游戏·ecmascript·harmonyos
0思必得06 小时前
[Web自动化] Selenium处理动态网页
前端·爬虫·python·selenium·自动化
东东5166 小时前
智能社区管理系统的设计与实现ssm+vue
前端·javascript·vue.js·毕业设计·毕设
catino6 小时前
图片、文件的预览
前端·javascript
2501_920931708 小时前
React Native鸿蒙跨平台实现推箱子游戏,完成玩家移动与箱子推动,当所有箱子都被推到目标位置时,玩家获胜
javascript·react native·react.js·游戏·ecmascript·harmonyos
layman05288 小时前
webpack5 css-loader:从基础到原理
前端·css·webpack
半桔8 小时前
【前端小站】CSS 样式美学:从基础语法到界面精筑的实战宝典
前端·css·html
AI老李8 小时前
PostCSS完全指南:功能/配置/插件/SourceMap/AST/插件开发/自定义语法
前端·javascript·postcss
_OP_CHEN8 小时前
【前端开发之CSS】(一)初识 CSS:网页化妆术的终极指南,新手也能轻松拿捏页面美化!
前端·css·html·网页开发·样式表·界面美化
啊哈一半醒8 小时前
CSS 主流布局
前端·css·css布局·标准流 浮动 定位·flex grid 响应式布局