在 JS 对象中键(字符串)的长度是否有限制?

因此,我们有一个例子,我们将有一个对象,其中的关键字是 id (int) ,值是字符串。但是我们注意到大多数情况下,我们根据字符串查找 id,所以我们决定反转它,使字符串成为键,值成为 id。因为这样我们就可以直接使用 var id = storage[text];,而不用浏览每个项目并比较值。下面是我们所做的实例。

下面是旧实现的例子:

var storage = {
0 : null,
1 : "Hello",
2 : "world!",
3 : "How are you?"
}

下面是新实现的例子:

var storage = {
"null" : 0,
"Hello" : 1,
"world!" : 2,
"How are you?" : 3
}

我明白了,现在字符串是键,可以为相同的字符串获取相同的 id。但是现在字符串可能非常大(机会很小,但是每个字符串可能最大1KB) ,JS 或 Android webview 对对象键有长度限制吗?

而且,这个实现有缺点吗? 到目前为止我还没有注意到任何问题,但是你永远不会知道。

70106 次浏览

No, there is no limit for the string length (as long as it fits into memory), and your implementation seems okay too. It's acutally quite common to have those 'turned around' arrays with e.g. boolean values. And as to the strings as keys: The strings are immutable symbols that are stored at a certain address, and what's actually used as the index for the array is that address (aka pointer aka reference) and not the string itself.

I have researched this a bit.

MDN is silent on the issue, and so is the spec (ES5, ES6). They only state that the property accessor must be a string, without any qualifications – in other words, there is no limit as far as the spec is concerned. That's hardly surprising.

How browsers handle it, is another matter. I have set up a test and run it in a number of browsers. Chrome 40 (Desktop), Chrome 40 (Android 5.1), Firefox 36, Opera 27, and IE9+ can deal with a property name of up to 227 characters. Safari 8 (OS X Yosemite) can even handle property names of 230 characters.

For all those browsers except IE, the maximum property length is the same as the maximum string length. IE9+ can handle a maximum string length of ~230 characters, but the limit for object keys is at 227 characters, just as in the other browsers.

The test didn't work in IE8 and Safari on iOS, presumably due to memory issues caused by the test code.

In a nutshell, it is safe to use long property names, even when taking it to extremes. As long as the strings themselves stay within the limits of what browsers can handle, you can use them as property names as well.

It appears as though with ECMAScript 2016, there is now a definitive answer to this question. According to the MDN Web Docs on string.length:

ECMAScript 2016 (ed. 7) established a maximum length of 2^53 - 1 elements. Previously, no maximum length was specified.

You can also find this specified in the ECMAScript® 2016 Language Specification:

The String type is the set of all ordered sequences of zero or more 16-bit unsigned integer values (“elements”) up to a maximum length of 253-1 elements.