javascript - Javascript 对象数组文字的可靠长度?

标签 javascript object-literal

有很多这样的问题,但是......呃......我无法让它工作。我如何...采用这样的对象文字:

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/

相关文章:

JavaScript 属性访问 : dot notation vs. 括号?

javascript - YouTube API、视频尺寸或宽高比

javascript - 如果 javascript 语句有问题

javascript - 使用 Plupload 和 Symfony3 抛出 ValidationException 时无响应

JavaScript 对象文字和 jQuery $(类)

javascript - JS对象文字中的这个 'method-like'语法是什么

python - 使用 python 重写 if-else 语句,如 javascript 对象字面量

javascript - 按子元素的数据 ID 对 li 进行排序 - jQuery

javascript - 如何从 Angular 6 或 7 组件内的 LESS 文件访问 style.less 中的 LESS 变量?

javascript - 将参数作为对象文字发送的更好方法?