string javascript中的整数长度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18143054/
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
integer length in javascript
提问by Ghoul Fool
Stoopid question time!
愚蠢的提问时间!
I know that in JavaScript you have to convert the integer to a string:
我知道在 JavaScript 中你必须将整数转换为字符串:
var num = 1024;
len = num.toString().length;
console.log(len);
My question is this: Why is there no get length property for integers in JavaScript? Is it something that isn't used that often?
我的问题是:为什么 JavaScript 中没有整数的 get length 属性?它是不是经常使用的东西?
回答by me_digvijay
Well, I don't think providing length properties to number will be helpful. The point is the length of strings does not change by changing its representation.
好吧,我认为为 number 提供长度属性不会有帮助。关键是字符串的长度不会通过改变它的表示而改变。
for example you can have a string similar to this:
例如,你可以有一个类似于这样的字符串:
var b = "sometext";
and its length property will not change unless you actually change the string itself.
除非您实际更改字符串本身,否则其长度属性不会更改。
But this is not the case with numbers.
但数字并非如此。
Same number can have multiple representations. E.g.:
同一个数字可以有多种表示。例如:
var a = 23e-1;
and
var b = 2.3;
So its clear that same number can have multiple representations hence, if you have length property with numbers it will have to change with the representation of the number.
所以很明显,相同的数字可以有多种表示,因此,如果你有数字的长度属性,它必须随着数字的表示而改变。
回答by IRvanFauziE
you must set variable toString()
first, like this:
您必须先设置变量toString()
,如下所示:
var num = 1024,
str = num.toString(),
len = str.length;
console.log(len);
回答by Frazer Kirkman
You can find the 'length' of a number using Math.log10(number)
您可以使用 Math.log10(number) 找到数字的“长度”
var num = 1024;
var len = Math.floor(Math.log10(num))+1;
console.log(len);
or if you want to be compatible with older browsers
或者如果您想与旧浏览器兼容
var num = 1024;
var len = Math.log(num) * Math.LOG10E + 1 | 0;
console.log(len);
The | 0
does the same this as Math.floor.
在| 0
做同样以此为Math.floor。