js中的undefined 与 null-编程思维

在 JavaScript 中, undefined 和 null 是两个特殊的值,用于表示缺失或空值。



undefined 是一个表示未定义或未赋值的原始值。它在以下情况下使用:

1. 变量声明了但未初始化时,默认为 undefined 。

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

 

 

2. 访问对象属性或数组元素时,如果该属性或元素不存在,则返回 undefined 。

let obj = { name: "John", age: 30 };
console.log(obj.address); // undefined

let arr = [1, 2, 3];
console.log(arr[3]); // undefined

 


3. 函数没有明确返回值时,默认返回 undefined 。

 

function foo() {
// 没有明确返回值
}

console.log(foo()); //undefined

 



相比之下, null 是一个表示空值或没有对象引用的特殊值。它通常由程序员显式赋予变量或属性,表示该值为空。例如:

let x = null;
console.log(x); // null

 


null 主要用于以下情况:

1. 初始化一个变量,以便稍后将其设置为对象。

let obj = null; // 初始化为 null
obj = { name: "John", age: 30 }; // 后续设置为对象

 

2. 表示函数的参数不具有对象引用。

function foo(arg) {
  if (arg === null) {
    console.log("参数为空");
  } else {
    console.log("参数不为空");
  }
}

foo(null); // 参数为空
foo("Hello"); // 参数不为空

 


需要注意的是, undefined 和 null 是不同的类型。 undefined 是一个类型为 undefined 的值,而 null 是一个类型为 object 的值。然而,在相等性比较( == 或 === )中,它们是相等的,因为它们都表示着相同的含义——空值。

console.log(undefined == null); // true
console.log(undefined === null); // false

 


在编程中,通常使用 undefined 来表示未定义或未赋值的状态,使用 null 来表示有意地将一个值设置为空。



当涉及到 undefined 和 null 的更多细节时,还有一些要注意的事项:

1. 类型检查

- 使用 typeof 操作符检查 undefined 值时,会返回字符串 "undefined" 。
- 使用 typeof 操作符检查 null 值时,会返回字符串 "object" 。这是一个历史遗留问题, null 被错误地标识为对象类型。

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

let y = null;
console.log(typeof y); // "object"

 

2. 默认参数值

- 当函数的参数没有传递或传递的值为 undefined 时,可以使用默认参数值。
- 当函数的参数传递 null 值时,会将 null 视为有效值,而不会触发默认参数值。

function foo(x = "default") {
    console.log(x);
}

foo(); // "default"
foo(undefined); // "default"
foo(null); // null

 

3. 安全导航操作符

- 使用安全导航操作符( ?. )可以避免访问对象属性或调用方法时出现 undefined 或 null 的错误。如果属性或方法不存在,则会返回 undefined 。

let obj = { name: "John", address: { city: "New York" } };

console.log(obj.address?.city); // "New York"
console.log(obj.address?.zipCode); // undefined

 

4. 变量赋值:

- 在变量赋值时, undefined 被视为一个变量可以接收的有效值。
- 而 null 被视为一个特殊值,通常用于表示空或未定义的状态。

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

let y = null;
console.log(y); // null

 

 

版权声明:本文版权归作者所有,遵循 CC 4.0 BY-SA 许可协议, 转载请注明原文链接
https://www.cnblogs.com/ronaldo9ph/p/17422449.html

js函数中的属性-编程思维

当定义和调用函数时,JavaScript 函数对象会自动具有一些特定的属性,以下是一些常见的属性和方法。 1. arguments : arguments 是一个类数组对象,它包含了函数调用时传递的参数。它允许你在函数内部访问传递给函数的参数列表,即使在函数定义时未明确声明这些参数。可以通过索引访问 arguments

linux中使用jenkins自动部署前端工程-编程思维

1、去年在自己的服务器上安装了jenkins,说用来自己研究一下jenkins自动化部署前端项目,jenkins安装好了,可是一直没管,最近终于研究了一下使用jenkins自动化部署,以此记录下来。 一、jenkins的安装 由于安装已经过去大半年时间了,具体步骤没有记录,可以到网上自行百度。 大致流程: 1、安装jd

快捷转换/互转 markdown 文档和 typescript/typedoc 注释-编程思维

背景 作为文档工具人,经常需要把代码里面的注释转换成语义化的 Markdown 文档,有时也需要进行反向操作。以前是写正则表达式全局匹配,时间长了这种方式也变得繁琐乏味。所以写了脚本来互转,增加一些便捷性。 解决方案 注释转 Markdown 下载地址:https://github.com/mazeyqian/go-g

web 前端常用正则校验规则-编程思维

Web 前端常用正则校验规则 作为 Web 前端开发,常用的正则校验规则有很多。下面是一些常见的示例: 1. 校验手机号码 手机号码的正则表达式可以根据不同国家和地区的手机号码格式进行调整。以下是中国大陆的手机号码正则表达式: const regex = /^1[3456789]\d{9}$/; 在这个示例中,正则表