.toLowerCase not working, replacement function?

后端 未结 5 586
感动是毒
感动是毒 2020-12-29 01:14

The .toLowerCase method is giving me an error when I try to use it on numbers. This is what I have:

var ans = 334;
var temp = ans.toLowerCase();         


        
相关标签:
5条回答
  • 2020-12-29 01:21

    It's not an error. Javascript will gladly convert a number to a string when a string is expected (for example parseInt(42)), but in this case there is nothing that expect the number to be a string.

    Here's a makeLowerCase function. :)

    function makeLowerCase(value) {
      return value.toString().toLowerCase();
    }
    
    0 讨论(0)
  • 2020-12-29 01:31

    It is a number, not a string. Numbers don't have a toLowerCase() function because numbers do not have case in the first place.

    To make the function run without error, run it on a string.

    var ans = "334";
    

    Of course, the output will be the same as the input since, as mentioned, numbers don't have case in the first place.

    0 讨论(0)
  • 2020-12-29 01:32
    var ans = 334 + '';
    var temp = ans.toLowerCase();
    alert(temp);
    
    0 讨论(0)
  • 2020-12-29 01:35

    .toLowerCase function only exists on strings. You can call toString() on anything in javascript to get a string representation. Putting this all together:

    var ans = 334;
    var temp = ans.toString().toLowerCase();
    alert(temp);
    
    0 讨论(0)
  • 2020-12-29 01:40

    Numbers inherit from the Number constructor which doesn't have the .toLowerCase method. You can look it up as a matter of fact:

    "toLowerCase" in Number.prototype; // false
    
    0 讨论(0)
提交回复
热议问题