Javascript - 如果(变量)检查' undefined'失败了

时间:2018-03-13 16:16:23

标签: javascript node.js rest undefined

if( !body || body[0] === '<') {...}

我使用上面的语句来检查变量bodyundefined还是null或除了预期值之外的任何值,但我一直得到一个TypeError:

TypeError: Cannot read property '0' of undefined

这怎么可能?根据检查未定义的非常流行的答案,如果body是null,undefined,NaN,&#34;&#34;,0,则上述语句的第一部分!body应返回true ,或者是假 - 因此不评估OR条件的右侧:body[0] === '<'在这种情况下。

Is there a standard function to check for null, undefined, or blank variables in JavaScript?

我还可以检查哪些内容以确保仅在body[0]未定义时才调用body?我也已尝试使用相同的描述行为if(typeof body === 'undefined' || body[0] === '<')。对此的任何想法将受到高度赞赏。谢谢。

(仅供参考:body是REST-API请求的响应,如果一切顺利,它将返回一个可以解析为JSON对象的字符串。但是,在某些情况下,整个HTML返回-file(包含错误信息),因此我在响应开始时检查&#39;&lt;&#;;有时变量似乎未定义&#39;抛出检查body[0]时出错。)

3 个答案:

答案 0 :(得分:1)

我认为你有倒退的逻辑。

&#13;
&#13;
function isFirstCharLt(value) {
  return !!value && typeof value === 'string' && value[0] === '<';
}

console.log(isFirstCharLt(undefined));
console.log(isFirstCharLt(null));
console.log(isFirstCharLt('<string'));
console.log(isFirstCharLt('string'));
&#13;
&#13;
&#13;

答案 1 :(得分:1)

你没有向我们展示所有的密码;)

如果bodyundefined,则会运行代码块,因为它会在if语句中快捷方式||,并且我怀疑您在该代码块中的某处检查body[0]

if (!body || body[0] === '<') {
  // is body[0] used here? 
}

最好确保body具有正确的属性,例如

if (typeof body === 'string' && body[0] === '<') {}

答案 2 :(得分:0)

我会使用两个if语句,检查它是否先定义然后验证:

if(body) {
  if (body[0] !== '<') {
    'DO-SOMETHING'
  }
}
相关问题