javascript string的最大长度是多少?

JavaScript09

javascript string的最大长度是多少?,第1张

Integer.MAX_VALUE=2147483647(string 理论长度) 

可以查一下 String 和 StringBuffer 获得长度的方法:

public int length()

Returns the length of this string. The length is equal to the number of 16-bit Unicode characters in the string.

获得 String 和 StringBuffer 的长度的方法都是 int length()

下面就可以计算出他们的最大长度了;

int 是一个 32 位变量类型,取正数部分来算的话,他们最长可以有 2^31-1 = 2147483647 个 16-bit Unicode character(理论长度)

共 2147483647 * 16 = 34359738352 位

34359738352 / 8 = 4294967294 (Byte)

4294967294 / 1024 = 4194303.998046875 (KB)

4194303.998046875 / 1024 = 4095.9999980926513671875 (MB)

4095.9999980926513671875 / 1024 = 3.99999999813735485076904296875 (GB)

有近 4G 的容量。

在 JavaScript 中,使用字符串的 length 属性可以读取字符串的长度。长度以字符为单位,该属性为只读属性。

下面代码使用字符串的 length 属性获取字符串的长度。

var s = "String 类型长度" //定义字符串

console.log(s.length) //返回10个字符

JavaScript 支持的字符包括单字节、双字节两种类型,为了精确计算字符串的字节长度,可以采用下面方法来计算。