有很多这样的问题,但是......呃......我无法让它工作。我如何...采用这样的对象文字:
locations = {};
locations.activities = [
{ text:'biking'},
{ text:'hiking'},
{ text:'boating'},
{ text:'studying'},
{ text:'reading'},
];
并打印出事件数组值?
IE 和 Firefox 的长度不同(分别为 6 和 5)。
谢谢
最佳答案
问题在于尾随逗号:出于跨浏览器兼容性原因将其删除。
导致行为不一致的原因是当存在尾随逗号时,某些浏览器会错误地解析文字1。正确的行为是ignore the trailing comma 2:
<小时/>If an element is elided at the end of an array (i.e. [...,]), that element does not contribute to the length of the Array.
1 该语法在 IE10 中正确工作,但在 IE9 及更早版本中不正确。这可以通过在相关浏览器模式下从控制台测试 [1,].length
来验证。报告的值分别为 1(正确)和 2(错误)。
2 尾随逗号与 [,]
相关,应等效于 [undefined]
。
关于javascript - Javascript 对象数组文字的可靠长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18541937/