因此,我们有一个对象,其中键是 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 对对象键有长度限制吗?
另外,这种实现有缺点吗?到目前为止我还没有注意到任何问题,但你永远不知道。
我对此进行了一些研究。
MDN沉默了关于这个问题,规格也是如此(ES5, ES6)。他们只是声明属性访问器必须是字符串,没有任何限定——换句话说,就规范而言没有任何限制。这并不奇怪。
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.
该测试在 iOS 上的 IE8 和 Safari 中不起作用,大概是由于测试代码引起的内存问题。
简而言之,使用长属性名称是安全的,即使在极端情况下也是如此。只要字符串本身不超出浏览器可以处理的范围,您就可以将它们用作属性名称。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)