gpt4 book ai didi

javascript - 如何在不使用 try/catch 的情况下解决 "cannot read property ... of undefined"问题?

转载 作者:行者123 更新时间:2023-12-02 17:21:06 25 4
gpt4 key购买 nike

此函数旨在计算特定类型数组中的所有项目。但是,当某种类型的元素为零时,我收到“无法读取未定义的属性...”错误。我尝试使用 typeof 关键字修复它,但没有成功。我的语法正确吗?我该如何解决这个问题?

function typeCount(type){
if (typeof (base.getbyType(type)) === "undefined"){ return 0; }
else { return base.getbyType(type).length;}
}
var pCount = typeCount('pen');

最佳答案

只需让 getbyType 在没有匹配项时返回一个空数组 - 然后不需要检查:

function typeCount(type){
return base.getbyType(type).length;
}

但是,如果发布的代码引发异常,则错误在其他地方 - 例如,不是 .length 访问所固有的。考虑以下可能的原因:

  • base 本身的计算结果为未定义。正确的解决方法是确保base不能未定义。这里的守卫只是隐藏了问题,应该被使用!

  • 异常是从 getbyType 内部引发的。这意味着该功能已损坏 - 修复它。

  • getbyType 不一致,仅有时返回未定义。这意味着该功能已损坏 - 修复它。

并且,如果 getbyType 坚持返回没有匹配的空数组,请使用临时变量。这也避免了原始代码所做的不必要的重复工作。

function typeCount(type){
var res = base.getbyType(type);
return (typeof res === "undefined") ? 0 : res.length;
}

或者,不关心它是否严格未定义(null.length 有什么好处?)..

function typeCount(type){
var res = base.getbyType(type);
return res ? res.length : 0;
}

或者,如果我们感觉“聪明”(请注意 getbyType 仍然只调用一次)..

function typeCount(type){
return (base.getbyType(type) || []).length;
}

关于javascript - 如何在不使用 try/catch 的情况下解决 "cannot read property ... of undefined"问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23947677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com