PHP前端开发

你需要了解的 JavaScript 特性

百变鹏仔 3天前 #JavaScript
文章标签 特性

在本文中,我们将探讨如何在尝试访问可能未定义或 null 的数据时防止错误,并且我们将研究在必要时可用于有效管理数据的方法。

通过可选链接进行安全访问

在 javascript 中,当尝试访问嵌套对象中的值或函数时,如果结果为 undefined,您的代码可能会抛出错误。此错误可能会停止代码的执行。但是,如果使用可选链接运算符,当尝试访问对象内的值或函数时,如果该值或函数不存在,它将返回 undefined 而不是抛出错误。这可以防止您的代码崩溃。

示例:

const person = {  name: 'john',  address: {    city: 'new york'  }};console.log(person.address?.city); // 'new york'console.log(person.address?.country); // undefined, no error

空值合并

如果变量的值为null 或未定义,它可能会破坏您的代码。要在变量为 null 或未定义时分配默认值,** 您可以使用 nullish 合并运算符 (??)。**

示例:

function getconfig(config) {    return config ?? { timeout: 1000, retries: 3 };}let userconfig = null;let finalconfig = getconfig(userconfig); // { timeout: 1000, retries: 3 } console.log(finalconfig);

使用 set 和 weakset 管理重复项

使用 set 删除重复项:

立即学习“Java免费学习笔记(深入)”;

如果数组包含重复值,您可以使用 set 删除这些重复项。以下是如何使用此结构:

const numbers = [1, 2, 3, 4, 4, 5, 6, 6, 7, 8, 9, 9];const uniquenumbers = [...new set(numbers)];console.log(uniquenumbers); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

使用 wea​​kset 防止重复:

由于weakset 保存对对象 的引用,因此一个对象只能添加到weakset 一次。这是一个例子:

// Creating a WeakSetconst weakset = new WeakSet();// Defining objectsconst obj1 = { name: 'Alice' };const obj2 = { name: 'Bob' };// Adding objects to the WeakSetweakset.add(obj1);weakset.add(obj2);console.log(weakset.has(obj1)); // trueconsole.log(weakset.has(obj2)); // true// Attempting to add the same object againweakset.add(obj1); // obj1 is already present, won't be added againconsole.log(weakset.has(obj1)); // trueconsole.log(weakset.has(obj2)); // true// Removing an object from the WeakSetweakset.delete(obj1);console.log(weakset.has(obj1)); // false// Adding the object againweakset.add(obj1);console.log(weakset.has(obj1)); // true

结论

在本文中,我们探讨了一些重要的概念,这些概念可以帮助防止在访问可能未定义或为 null 的值时发生错误,以及在必要时更有效地管理数据的方法。