toUpperCase() is not making the string upper case

前端 未结 7 1856
我在风中等你
我在风中等你 2021-02-11 03:10

I don\'t know what I\'m doing wrong; But somehow .toUpperCase() String-function is not working on my browser or do I get something wrong?

var string          


        
7条回答
  •  一向
    一向 (楼主)
    2021-02-11 03:19

    Previous answers about Strings being immutable are great! Here is just another potential run-time reason for getting this error which might be hard to spot at first. It does not detract from any of the above valid answers:

    If the object on which the .toUpperCase() method is invoked is not a String, then the runtime doesn't 'find' the method toUpperCase() since that method/function only exists on String objects.

    e.g. console.log(variableName.toUpperCase());

    If variableName is of the type String, it works fine. If it is of another type (that does not have a toUpperCase() method, it says 'toUpperCase() is not a function (since it isn't).

    If you know it should be a string, you can cast it like this:

    console.log(String(variableName).toUppercase());
    

    Hope it helps.

提交回复
热议问题