
在本文中,我们将探讨如何在尝试访问可能未定义或 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 删除重复项:
千博购物系统.Net能够适合不同类型商品,为您提供了一个完整的在线开店解决方案。千博购物系统.Net除了拥有一般网上商店系统所具有的所有功能,还拥有着其它网店系统没有的许多超强功能。千博购物系统.Net适合中小企业和个人快速构建个性化的网上商店。强劲、安全、稳定、易用、免费是它的主要特性。系统由C#及Access/MS SQL开发,是B/S(浏览器/服务器)结构Asp.Net程序。多种独创的技术使
立即学习“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]
使用 weakset 防止重复:
由于weakset 保存对对象 的引用,因此一个对象只能添加到weakset 一次。这是一个例子:
// Creating a WeakSet
const weakset = new WeakSet();
// Defining objects
const obj1 = { name: 'Alice' };
const obj2 = { name: 'Bob' };
// Adding objects to the WeakSet
weakset.add(obj1);
weakset.add(obj2);
console.log(weakset.has(obj1)); // true
console.log(weakset.has(obj2)); // true
// Attempting to add the same object again
weakset.add(obj1); // obj1 is already present, won't be added again
console.log(weakset.has(obj1)); // true
console.log(weakset.has(obj2)); // true
// Removing an object from the WeakSet
weakset.delete(obj1);
console.log(weakset.has(obj1)); // false
// Adding the object again
weakset.add(obj1);
console.log(weakset.has(obj1)); // true
结论
在本文中,我们探讨了一些重要的概念,这些概念可以帮助防止在访问可能未定义或为 null 的值时发生错误,以及在必要时更有效地管理数据的方法。









