【问题标题】:true == false evaluates to true somehow?true == false 以某种方式评估为 true?
【发布时间】:2015-03-20 17:54:19
【问题描述】:

我一直在努力抓取一些使用 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 的奇怪之处吗(我知道我们没有使用严格的 === 相等性,但说真的......)?

【问题讨论】:

  • 这永远不会发生。 if(true == false) console.log('WTF!');
  • 这个例子正好发生了这种情况,或者你假设在} else if(true == false) {中生成了一个true
  • if(true == false) 没有意义。
  • 也许开发人员想“注释掉”那段代码,但这并不能解释为什么他不简单地使用 if (false)/* comment block */
  • 显示使用该问题的示例。喜欢:console.log(isValidDomain(x, y));

标签: javascript conditional-statements


【解决方案1】:

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

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>

【讨论】:

    【解决方案2】:

    我会说 Blazemonger 很可能是正确的。

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

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

    【讨论】:

      猜你喜欢
      • 2015-03-15
      • 1970-01-01
      • 2020-12-15
      • 2015-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-16
      • 2023-03-29
      相关资源
      最近更新 更多