【JavaScript基础】Undefined类型详解

97 阅读1分钟

image.png

在JavaScript中,Undefined是一个原始数据类型,表示变量尚未被赋值,或者对象属性不存在。

1. Undefined类型主要场景

1)变量声明但未赋值

    let x;
    console.log(x); // undefined
    console.log(typeof x); // undefined

    var y;
    console.log(y); // undefined
    console.log(typeof y); // undefined

2)函数没有返回值

    function noReturn() {
      // 没有return语句
    }
    console.log(noReturn()); // undefined

3)函数参数未传递

    function greet(name) {
      console.log(name); // undefined
    }
    greet();

    function sum(a, b) {
      console.log(a, b); // 7 undefined
    }
    sum(7);

4)访问对象不存在的属性

    const obj = { name'cxh' };
    console.log(obj.age); // undefined

    const arr = [123];
    console.log(arr[3]); // undefined

5)数组稀疏位置

    const sparseArray = [1, , 3];
    console.log(sparseArray[1]); // undefined

6)函数的return语句没有指定返回值

    function emptyReturn() {
      return;
    }
    console.log(emptyReturn()); // undefined

7)解构赋值中不存在的属性

    const { nonExistent } = {};
    console.log(nonExistent); // undefined

    const [first, , third] = [12];
    console.log(third); // undefined

8)void操作符的结果

    console.log(void 0); // undefined
    console.log(void (1 + 1)); // undefined

9)访问全局对象不存在的属性

    // 在浏览器环境中
    console.log(window.nonExistentProperty); // undefined

2. 检测Undefined的方法

1)严格相等

    let value;
    if (value === undefined) {
      console.log('value is undefined'); // value is undefined
    }

2)typeof 操作符

    let value;
    if (typeof value === 'undefined') {
      console.log('value is undefined'); // value is undefined
    }

3)void 0

    let value;
    if (value === void 0) {
      console.log('value is undefined'); // value is undefined
    }

3. http请求中undefined属性值的处理机制

在http请求中,当请求体(body)中的对象属性值为undefined时,这些属性通常会在序列化过程中被丢弃或忽略,不会包含在最终的请求参数中。

    const data = {
      name'cxh',
      ageundefined,
      addressundefined
    };

    // Fetch方式
    fetch('/api', {
      method'POST',
      headers: {
        'Content-Type''application/json'
      },
      bodyJSON.stringify(data) // age和address属性被丢弃
    });

    // Ajax方式
    const xhr = new XMLHttpRequest();
    xhr.open('POST''/api');
    xhr.setRequestHeader('Content-Type''application/json');
    xhr.send(JSON.stringify(data)); // age和address属性被丢弃