对于空对象给出 TypeError: 无法将未定义或空转换为对象
好吧,我知道这是一个非常常见的问题,但我尝试找到解决方案,但还没有成功。所以这里是问题陈述:
由于某些情况,我的对象没有值并且它是空的
{
,当我尝试使用
Object.keys(ambassador).length
或
Object.entries(ambassador).length
检查此对象的长度时,它给了我错误
TypeError: Cannot convert undefined or null to object.
代码示例:
const ambassador = Array.isArray(ambassadors)
? ambassadors.find((item) => {
return item.affiliate_id === affiliate.tracking_id;
})
: {};
console.log(ambassador == null); //false
console.log(typeof(ambassador)); // Object
console.log(Object.keys(ambassador).length > 0 ); //TypeError: Cannot convert undefined or null to object.
因此,我从 Kireeti Ganisetti 的评论中得到了解决方案,他建议使用 LOADASH 并且它有效 :)
在 Javascript - React 中检查对象是否为空:
import _ from 'lodash';
_.isEmpty(ambassador)
The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values and is treated as falsy for boolean operations
在读取键之前,尝试检查对象是否不为
null
:
let ambassador = null;
console.log(ambassador == null); //false
console.log(typeof(ambassador)); // Object
if (ambassador)
console.log(Object.keys(ambassador).length > 0 );
一个例子:
let ambassador = null;
console.log(ambassador == null); //false
console.log(typeof(ambassador)); // Object
if (ambassador)
console.log(Object.keys(ambassador).length > 0 );
更新:
如果
let ambassador = {};
则
abmassador
为
truthy
,因此您可以检查对象的键:
let ambassador = {};
console.log(ambassador == null); //false
console.log(typeof(ambassador)); // Object
if (ambassador)
console.log(`ambassador`, Object.keys(ambassador).length > 0 );
In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, 0n, "", null, undefined, and NaN).
JavaScript 中的真值示例(在布尔上下文中将被强制为 true,从而执行 if 块):
if (true)
if ({})
if ([])
if (42)
if ("0")