true == false 以某种方式评估为 true ?

true == false evaluates to true somehow?

我一直在努力抓取一些使用 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;
}

据我所知,一定有执行此代码的实例; result = current.endsWith('.' + target);。鉴于 true == false 本质上是错误的,代码将如何达到该声明?这是 JS 的一些奇怪之处吗(我知道我们没有使用严格的 === 相等性,但是认真的......)?

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

else if 可能在某个时候有一些其他条件,并且出于某种原因,他们决定不再希望该代码块执行,因此他们将条件更改为始终假的。

程序员使用 1 === 0 作为 false 的指示也并不少见。他们为什么要这样做是任何人的猜测。

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

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>