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

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


当前回答

为了求长度,你必须把数字变成字符串

var num = 123;

alert((num + "").length);

or

alert(num.toString().length);

其他回答

在一次测试中,我也被问到类似的问题。

找到一个数字的长度而不转换为字符串

const numbers = [1, 10, 100, 12, 123, -1, -10, -100, -12, -123, 0, -0]

const numberLength = number => {

  let length = 0
  let n = Math.abs(number)

  do {
    n /=  10
    length++
  } while (n >= 1)

  return length
}

console.log(numbers.map(numberLength)) // [ 1, 2, 3, 2, 3, 1, 2, 3, 2, 3, 1, 1 ]

负数的添加使它更加复杂,因此Math.abs()。

试试这个:

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

它在使用中的例子

我想纠正@Neal的答案,这对整数来说很好,但在前一种情况下,数字1将返回0的长度。

function Longueur(numberlen)
{
    var length = 0, i; //define `i` with `var` as not to clutter the global scope
    numberlen = parseInt(numberlen);
    for(i = numberlen; i >= 1; i)
    {
        ++length;
        i = Math.floor(i/10);
    }
    return 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.

有三种方法。

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