Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/467.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Javascript中捕获未捕获的类型错误_Javascript_Error Handling_Undefined - Fatal编程技术网

在Javascript中捕获未捕获的类型错误

在Javascript中捕获未捕获的类型错误,javascript,error-handling,undefined,Javascript,Error Handling,Undefined,获取以下错误 Uncaught Typerror : Cannot read property 'foo' of undefined 冒犯的界线是 s2 = targets[j].foo*4; 显然,我应该修复问题的根源,但与此同时,如何正确地包装有问题的行,使其不会抛出错误并中断我的应用程序?错误的可能原因是该特定索引的目标[j]为空 试试这个 s2 = targets[j] && targets[j].foo ? targets[j].foo * 4 : 0; 如果ta

获取以下错误

Uncaught Typerror : Cannot read property 'foo' of undefined
冒犯的界线是

s2 = targets[j].foo*4;

显然,我应该修复问题的根源,但与此同时,如何正确地包装有问题的行,使其不会抛出错误并中断我的应用程序?

错误的可能原因是该特定索引的
目标[j]
为空

试试这个

s2 = targets[j] && targets[j].foo ? targets[j].foo * 4 : 0;
如果
targets[j]
为空或未定义,您可以将s2的值设置为默认值(我将其设置为0)


同样,这只会修复问题的症状,而不是问题的根源。

将代码包装在try-catch中可以让您处理类似的问题

try {
    s2 = targets[j].foo * 4;
} catch (exception) {
    console.error(exception.stack);
}
而不是

Uncaught ReferenceError: targets is not defined
(因为我甚至没有定义目标)我现在得到

ReferenceError: targets is not defined
    at snippets:///424_2145:2:10 
但你是对的,你应该找到根本原因