true==false以某种方式计算为true

true == false evaluates to true somehow?

本文关键字:true 计算 方式 false      更新时间:2023-09-26

我一直在努力抓取一些使用OWASP CRSFGuard项目进行保护的网页。图书馆似乎导致我的一个请求获得401,所以我开始深入研究他们的代码,并注意到以下内容;

function isValidDomain(current, target) {
    var result = false;
    /** check exact or subdomain match **/
    if(current == target || current == 'localhost') {
        result = true;
    } else if(true == false) {
        if(target.charAt(0) == '.') {
            result = current.endsWith(target);
        } else {
            result = current.endsWith('.' + target);
        }
    }
    return result;
}

据我所知,一定有执行此代码的实例;CCD_ 1。假设true == false本质上是false,那么代码将如何到达该语句?这是JS的古怪之处吗(我知道我们没有使用严格的===等式,但说真的…)?

答案:它永远不会到达那个代码块。

function isValidDomain(current, target) {
  var result = false;
  /** check exact or subdomain match **/
  if (current == target || current == 'localhost') {
    result = true;
  } else if (true == false) {
    if (target.charAt(0) == '.') {
      result = current.endsWith(target);
    } else {
      result = current.endsWith('.' + target);
    }
  }
  return result;
}
var trueFalse = document.getElementById('trueFalse');
trueFalse.innerHTML = isValidDomain('true', 'false') ? 'WTF!' : 'All is good in the JS World';
trueFalse.addEventListener('click', function(e) {
  trueFalse.innerHTML = (true == false) ? 'WTF!' : 'All is good in the JS World Still';
});
<div id="trueFalse"></div>

我认为Blazemonger很可能是正确的。

else if可能在某个时候有其他条件,无论出于什么原因,他们决定不想再执行该代码块,所以他们将条件更改为始终为false的条件。

程序员使用1 === 0作为false的指示也并不罕见。他们为什么要这么做,谁也猜不透。