在本文中,我们将探讨如何在尝试访问可能未定义或 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或undefined,为了避免这种情况,可以使用nullish coalescing运算符
示例 :
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 letter= ["a", "b", "c" , "c" , "a" , "d" ,"d" ,]; const result= [...new set(letter)]; console.log(result) => ["a", "b" , "c" , "d"]
使用 weakset 防止重复 :
由于 weakset 保存对对象 的引用,因此对象只能添加到 weakset 一次。
示例 :
// Creating a WeakSet const weakset = new WeakSet(); // Defining objects const personJane = { name: 'jane' }; const personMike = { name: 'mike' }; // Adding objects to the WeakSet weakset.add(personJane); weakset.add(personMike); 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号