我要在JavaScript或jQuery中获得一个数字的长度?

我尝试过价值。长度没有任何成功,我需要先将其转换为字符串吗?


当前回答

如果不把整数转换成字符串,你可以做一个奇怪的循环:

var number = 20000;
var length = 0;
for(i = number; i > 1; ++i){
     ++length;
     i = Math.floor(i/10);
}

alert(length);​

演示:http://jsfiddle.net/maniator/G8tQE/

其他回答

试试这个:

$("#element").text().length;

它在使用中的例子

一种用于整数或整数部分长度的方法,无需将其常规转换为字符串:

var num = 9999999999; // your number
if (num < 0) num = -num; // this string for negative numbers
var length = 1;
while (num >= 10) {
   num /= 10;
   length++;
}
alert(length);

是的,你需要转换为字符串,以找到长度。例如

var x=100;// type of x is number
var x=100+"";// now the type of x is string
document.write(x.length);//which would output 3.

也可以使用模板字符串:

const num = 123456
`${num}`.length // 6

你应该使用最简单的字符串(stringLength),可读性总是胜过速度。但如果你关心速度,下面有一些。

三种不同的方法,速度各不相同。

// 34ms
let weissteinLength = function(n) { 
    return (Math.log(Math.abs(n)+1) * 0.43429448190325176 | 0) + 1;
}

// 350ms
let stringLength = function(n) {
    return n.toString().length;
}

// 58ms
let mathLength = function(n) {
    return Math.ceil(Math.log(n + 1) / Math.LN10);
}

// Simple tests below if you care about performance.

let iterations = 1000000;
let maxSize = 10000;

// ------ Weisstein length.

console.log("Starting weissteinLength length.");
let startTime = Date.now();

for (let index = 0; index < iterations; index++) {
    weissteinLength(Math.random() * maxSize);
}

console.log("Ended weissteinLength length. Took : " + (Date.now() - startTime ) + "ms");


// ------- String length slowest.

console.log("Starting string length.");
startTime = Date.now();

for (let index = 0; index < iterations; index++) {
    stringLength(Math.random() * maxSize);
}

console.log("Ended string length. Took : " + (Date.now() - startTime ) + "ms");


// ------- Math length.

console.log("Starting math length.");
startTime = Date.now();

for (let index = 0; index < iterations; index++) {
    mathLength(Math.random() * maxSize);
}