
在本文中,我们将探讨如何在尝试访问可能未定义或 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 删除重复项:
立即学习“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 的值时发生错误,以及在必要时更有效地管理数据的方法。
以上就是你需要了解的 JavaScript 特性的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号