不要JavaScript数组和对象有一组订单? [英] Do javascript arrays and objects have a set order?

查看:119
本文介绍了不要JavaScript数组和对象有一组订单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这问题是我的创建涉及从JSON对象HTML表格当前的项目之一是至关重要的。我想我可以创造条件,使他们为HTML之前我的数组/对象进行排序的功能。我唯一​​担心的是,为了不JavaScript的事,如果我是创建一个新的阵列使用相同的数据(以不同的顺序)作为另一个阵列他们最终会是相同的。

This question is vital to one of my current projects involving creating HTML tables from JSON objects. I was thinking I could create functions that would sort my Arrays/Objects before rendering them as HTML. My only concern is that order doesn't matter in JavaScript, and if I were to create a new Array with the same data (in a different order) as another Array they would end up identical.

我想不出一个快速的方法来测试这一点,所以我问在这里。

I can't think of a fast way to test this, so I'm asking here.

推荐答案

其他回答阵列上,所以我只是想提供对象的某些信息。

Others have answered on arrays, so I just wanted to provide some info on objects.

在说,这个标准是不存在的,但它的实际的定义是,一个对象将插入顺序列举,所不同的是数字按升序排列并首先列举。我说一般,但这种行为是隔靴搔痒标准(也没有像jQuery框架规范它,据我所知)。

On that, the standard is non-existent, but it's de facto definition is that an object will enumerate in insertion order, with the exception that numbers are placed in ascending order and enumerated first. I say typically, but this behavior is nowhere near standardized (nor do frameworks like jQuery standardize it, AFAIK).

您可以测试使用该浏览器的jsfiddle:

You can test browsers using this jsFiddle:

http://jsfiddle.net/7cCpu/4/

对象 {富:酒吧,吧:富,巴兹:巴兹,3:3,2:2,1 :1} 列举如下:

foo, bar, baz, 3, 2, 1 // insertion order

1, 2, 3, foo, bar, baz // Chrome enumeration
1, 2, 3, foo, bar, baz // Opera
1, 2, 3, foo, bar, baz // IE9
foo, bar, baz, 3, 2, 1 // Firefox (!!!)

我没有安装Safari浏览器,但我的假设的是一样的Chrome。在任何情况下,关键是你的可以的做出假设 - 它不是随机的 - 但它可能是一个更好的主意,如果你依赖于准确的枚举使用数组

I don't have Safari installed, but I assume it's the same as Chrome. In any case, the point is that you can make assumptions -- it's not random -- but it's probably a better idea to use an array if you depend on exact enumeration.

均匀厉害是杜里指出以上,其中删除和替换的关键变造的事情进一步的价值。看的时候我会发生什么吧删除 Object.bar =富然后枚举:

Even nastier is what duri pointed out above, where deleting and replacing the value for a key alters things further. Watch what happens when I delete bar and do Object.bar = "foo" then enumerate:

1, 2, 3, foo, baz, bar // Chrome enumeration
1, 2, 3, foo, baz, bar // Opera
1, 2, 3, foo, bar, baz // IE9 (!!!)
foo, baz, 3, 2, 1, bar // Firefox (!!!)

这篇关于不要JavaScript数组和对象有一组订单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆