愚蠢的提问时间!
我知道在 JavaScript 中你必须将整数转换为字符串:
var num = 1024;
len = num.toString().length;
console.log(len);
我的问题是:为什么 JavaScript 中没有整数的长度属性?它是不经常使用的东西吗?
愚蠢的提问时间!
我知道在 JavaScript 中你必须将整数转换为字符串:
var num = 1024;
len = num.toString().length;
console.log(len);
我的问题是:为什么 JavaScript 中没有整数的长度属性?它是不经常使用的东西吗?
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.
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.
您必须先设置变量toString()
,如下所示:
var num = 1024,
str = num.toString(),
len = str.length;
console.log(len);
您可以使用 Math.log10(number) 找到数字的“长度”
var num = 1024;
var len = Math.floor(Math.log10(num))+1;
console.log(len);
或者如果您想与旧版浏览器兼容
var num = 1024;
var len = Math.log(num) * Math.LOG10E + 1 | 0;
console.log(len);
与 Math.floor的| 0
作用相同。