Javascript .toLowerCase 不工作,替换功能?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12611609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:49:54  来源:igfitidea点击:

.toLowerCase not working, replacement function?

javascriptstringlowercase

提问by Lucas

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

.toLowerCase当我尝试在数字上使用该方法时,它给了我一个错误。这就是我所拥有的:

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

And then it gives me this error:

然后它给了我这个错误:

'undefined' is not a function (evaluating 'ans.toLowerCase()')

I don't know where I got this wrong. I always thought that numbers can also be parsed, with no change in result (maybe that's where I stuffed up).

我不知道我哪里出错了。我一直认为数字也可以解析,结果没有变化(也许这就是我塞满的地方)。

But if that's not the error, can someone write a custom makeLowerCasefunction, to make the string lower case, perhaps using regex or something?

但如果这不是错误,有人可以编写一个自定义makeLowerCase函数,使字符串小写,也许使用正则表达式或其他东西?

回答by spender

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

.toLowerCase 函数只存在于字符串上。您可以对 javascript 中的任何内容调用 toString() 以获取字符串表示形式。把这一切放在一起:

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

回答by 0x499602D2

Numbers inherit from the Numberconstructor which doesn't have the .toLowerCasemethod. You can look it up as a matter of fact:

数字从Number没有该.toLowerCase方法的构造函数继承。事实上,你可以查一下:

"toLowerCase" in Number.prototype; // false

回答by Guffa

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.

这不是错误。当需要字符串时,Javascript 很乐意将数字转换为字符串(例如parseInt(42)),但在这种情况下,没有任何东西期望数字是字符串。

Here's a makeLowerCasefunction. :)

这是一个makeLowerCase函数。:)

function makeLowerCase(value) {
  return value.toString().toLowerCase();
}

回答by Joe Coder

var ans = 334 + '';
var temp = ans.toLowerCase();
alert(temp);

回答by Quentin

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

它是一个数字,而不是一个字符串。数字没有toLowerCase()功能,因为数字首先没有大小写。

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.

当然,输出将与输入相同,因为如前所述,数字首先没有大小写。