简体   繁体   English

潜在的null / undefined变量的访问属性-javascript

[英]accessing property of potential null/undefined variable - javascript

i'm analyzing my code using sonarqube and am running into an issue with the following code: 我正在使用声纳分析我的代码,并遇到以下代码问题:

var backtoyear = $('#backtoyear').val();

if (backtoyear != undefined || backtoyear.length > 0) {
   var currentyear = (new Date()).getFullYear();
   var numberofyears = currentyear - backtoyear;
}

the backtoyear.length variable is causing an "TypeError can be thrown as "backtoyear" might be null or undefined here." backtoyear.length变量导致“可能引发TypeError,因为“ backtoyear”在此处可能为null或未定义。” because it could potential be null/undefined and therefore won't have any properties. 因为它可能为null /未定义,因此将没有任何属性。

should i just remove the second have of the OR from the if condition? 我应该从if条件中删除OR的第二个条件吗?

You can simplify your following statement, 您可以简化以下声明,

if (backtoyear != undefined || backtoyear.length > 0) {

to

if (backtoyear) {

This is more readable, efficient and understandable. 这更具可读性,效率和可理解性。

Refer to this specification ToBoolean 参考此规范ToBoolean

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM