在React Native(RN)中,null 和 undefined 是 JavaScript 中的两个特殊值,分别表示不同的含义:
undefined 表示一个变量被声明了,但还没有被赋值,或者当访问一个对象中不存在的属性时。
null 表示一个变量被明确地赋值为空值。
1、undefined 和null定义
undefined:
当访问一个对象中不存在的属性时,例如:
const obj = {};
console.log(obj.property); // 输出 undefined
当一个变量声明了但没有赋值时,例如:
let someVar;
console.log(someVar); // 输出 undefined
null:
当需要显式表示“没有值”或者“空”的时候,例如在组件的状态初始化中:
const [value, setValue] = useState(null);
当需要重置某个值,例如清除输入框的内容时:
setInputValue(null);
如何判断undefined和null
判断undefined
要判断一个变量是否为undefined,可以使用严格等于运算符(===):
let variable;
if (variable === undefined) {
console.log('The variable is undefined.');
} else {
console.log('The variable is defined.');
}
判断null
要判断一个变量是否为null,同样可以使用严格等于运算符(===):
let variable = null;
if (variable === null) {
console.log('The variable is null.');
} else {
console.log('The variable is not null.');
}
兼容判断undefined和null
有时候你可能想同时判断一个变量是否为null或undefined,可以使用宽松等于运算符(==)来同时判断:
let variable;
if (variable == null) {
console.log('The variable is either null or undefined.');
} else {
console.log('The variable is neither null nor undefined.');
}
因为在JavaScript中,null和undefined在宽松等于比较时被认为是相等的,但在严格等于比较中并不相等。
但是注意的是:直接用variable == undefined只能检测到undefined。
3、if(!xxx.xxxx)判断成立条件
在JavaScript中,当你使用if (config.jsonParams)语句时,条件成立的情况是config.jsonParams为真值(truthy)。如果config.jsonParams是undefined或null,该条件将不会成立。
let config = { jsonParams: undefined };
if (config.jsonParams) {
console.log('jsonParams is truthy.');
} else {
console.log('jsonParams is falsy.');
}
// 输出: 'jsonParams is falsy.'
config = { jsonParams: null };
if (config.jsonParams) {
console.log('jsonParams is truthy.');
} else {
console.log('jsonParams is falsy.');
}
// 输出: 'jsonParams is falsy.'
如果config本身是undefined或null,尝试访问config.jsonParams会导致运行时错误,因为你不能在undefined或null上访问属性。
4、运行时代码错误,且未捕获异常
如果代码在运行时遇到错误(如试图访问一个未定义或空对象的属性),并且该错误没有被捕获(catch),后续代码将不会执行。这种错误称为未捕获的异常。
捕获异常(推荐):使用try...catch语句可以捕获运行时错误,允许后续代码继续执行。
未捕获异常:如果运行时错误未被捕获,脚本会停止执行,后续代码将不会执行。
let config = undefined;
if (config.jsonParams) { // 这里会抛出一个错误
console.log('jsonParams is truthy.');
}
console.log('This code will not run.'); // 这行代码不会执行
// 输出:
// Uncaught TypeError: Cannot read properties of undefined (reading 'jsonParams')
使用try{}catch(error){}捕获异常
let config = undefined;
try {
if (config.jsonParams) {
console.log('jsonParams is truthy.');
}
} catch (error) {
console.log('Caught an error:', error.message);
}
console.log('This code will still run.');
// 输出:
// Caught an error: Cannot read properties of undefined (reading 'jsonParams')
// This code will still run.
网友评论