Javascript string/integer comparisons

后端 未结 8 928
太阳男子
太阳男子 2020-11-22 16:34

I store some parameters client-side in HTML and then need to compare them as integers. Unfortunately I have come across a serious bug that I cannot explain. The bug seems to

相关标签:
8条回答
  • 2020-11-22 17:20

    The answer is simple. Just divide string by 1. Examples:

    "2" > "10"   - true
    

    but

    "2"/1 > "10"/1 - false
    

    Also you can check if string value really is number:

    !isNaN("1"/1) - true (number)
    !isNaN("1a"/1) - false (string)
    !isNaN("01"/1) - true (number)
    !isNaN(" 1"/1) - true (number)
    !isNaN(" 1abc"/1) - false (string)
    

    But

    !isNaN(""/1) - true (but string)
    

    Solution

    number !== "" && !isNaN(number/1)
    
    0 讨论(0)
  • 2020-11-22 17:22

    Comparing Numbers to String Equivalents Without Using parseInt

    console.log(Number('2') > Number('10'));
    console.log( ('2'/1) > ('10'/1) );
    
    var item = { id: 998 }, id = '998';
    var isEqual = (item.id.toString() === id.toString());
    isEqual;
    
    0 讨论(0)
提交回复
热议问题