代码之家  ›  专栏  ›  技术社区  ›  Kaddath

Javascript检查松散的比较,除了错误的值

  •  0
  • Kaddath  · 技术社区  · 7 年前

    我看了一会儿,但出乎意料的是,我还没有找到任何具体的答案。

    我想检查我们的数据集工具中的值是否发生了变化。为此,我希望使用松散比较,以便转换为字符串的等效数字(只是一个示例)不会被检测到或更改:

    42 != "42" // -> false
    

    然而,出于明显的原因,我希望严格比较虚假的比较,除非它们是等效的,例如:

    '' != 0 // -> false, i'd like true
    '0' != 0 // -> false, and that's OK
    null != false // -> true, and that's OK
    undefined != null // -> false, but should be true (this case is not the priority)
    

    有没有一种有效的方法可以在不手动列出所有案例的情况下做到这一点?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Taki    7 年前

    你可以用 parseInt

    const a = parseInt('') !== 0 // -> false, i'd like true
    const b = parseInt('0') !== 0 // -> false, and that's OK
    const c = parseInt(null) !== false // -> true, and that's OK
    const d = parseInt(undefined) !== null // -> false, but should be true (this case is not the priority)
    const x = parseInt(0) !== ''
    
    console.log(a, b, c, d, x);
        2
  •  0
  •   Kaddath    7 年前

    经过一些测试(许多测试失败,因为null没有属性,所以没有 .toString 我找到了合适的衣服,多亏了Taki的回答,parseInt才是关键 NaN 转变最初的想法只是问题本身在代码中的简单转换: (a && a != b) || (!a && a !== b) ,但它失败了 0 '0' 按照特定的顺序。所以我做了这个测试(如果a是真的似乎没有必要): (a != b) || (!a && parseInt(a) !== parseInt(b))

    function test(a, b){
      return (a != b) || (!a && parseInt(a) !== parseInt(b));
    }
    
    var a = test('', 0), // -> false, i'd like true
        b = test(0, ''),
        c = test(0, '0'), // -> false, and that's OK
        d = test('0', 0),
        e = test(null, false), // -> true, and that's OK
        f = test(false, null),
        g = test(undefined, null), // -> false, but should be true (this case is not the priority)
        h = test(null, undefined),
        i = test('', undefined), //all following are falsey and different, so true
        j = test(undefined, ''),
        k = test('', null),
        l = test(null, ''),
        m = test('0', undefined),
        n = test(undefined, '0'),
        o = test(null, '0'),
        p = test('0', undefined),
        q = test('1', true), //was not specified, but true is 1 in our DB, so false is OK
        r = test(true, '1'),
        s = test('42', 42), //also false, no change
        t = test(42, '42');
    
    console.log(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t);