我要在JavaScript或jQuery中获得一个数字的长度?
我尝试过价值。长度没有任何成功,我需要先将其转换为字符串吗?
我要在JavaScript或jQuery中获得一个数字的长度?
我尝试过价值。长度没有任何成功,我需要先将其转换为字符串吗?
当前回答
var x = 1234567;
String(x).length;
它比. tostring()(在接受的答案中)短。
其他回答
有三种方法。
var num = 123;
alert(num.toString().length);
性能一(ie11中性能最好)
var num = 123;
alert((num + '').length);
数学(在Chrome和firefox中表现最好,但在ie11中最慢)
var num = 123
alert(Math.floor( Math.log(num) / Math.LN10 ) + 1)
这里有一个jspref http://jsperf.com/fastest-way-to-get-the-first-in-a-number/2
为了求长度,你必须把数字变成字符串
var num = 123;
alert((num + "").length);
or
alert(num.toString().length);
也可以使用模板字符串:
const num = 123456
`${num}`.length // 6
var x = 1234567;
String(x).length;
它比. tostring()(在接受的答案中)短。
试试这个:
$("#element").text().length;
它在使用中的例子