Javascript检查是否存在虚假比较(假值除外)

时间:2019-02-11 14:40:27

标签: javascript comparison

我看了一段时间,但令我惊讶的是没有找到具体答案。

我想检查数据集工具中的值是否已更改。为此,我想使用松散比较,以便检测到转换为字符串的等效数字(仅作为示例)不会更改:

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 个答案:

答案 0 :(得分:1)

您可以使用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);

答案 1 :(得分:0)

经过一些测试(许多失败,因为null没有属性,所以没有.toString等),在塔基(Taki)的帮助下,我找到了合适的方法,感谢NaN转换,parseInt是关键。最初的想法只是用代码(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);