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.

这个问题对于我当前涉及从JSON对象创建HTML表的项目之一至关重要。我以为我可以创建在将它们呈现为HTML之前对我的数组/对象进行排序的函数。我唯一关心的是命令在JavaScript中无关紧要,如果我要创建一个具有相同数据(以不同顺序)的新数组作为另一个数组,它们最终会相同。

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

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

5 个解决方案

#1


9

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

其他人已回答数组,所以我只是想提供一些关于对象的信息。

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).

在那个,标准是不存在的,但事实上的定义是一个对象将按插入顺序枚举,除了数字按升序排列并首先枚举。我通常说,但这种行为远没有标准化(jQuery框架也没有标准化,AFAIK)。

You can test browsers using this jsFiddle:

您可以使用此jsFiddle测试浏览器:

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

The object {"foo":"bar", "bar":"foo", "baz":"baz", "3":3, "2":2, "1":1} enumerates as follows:

对象{“foo”:“bar”,“bar”:“foo”,“baz”:“baz”,“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 (!!!)

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.

我没有安装Safari,但我认为它与Chrome相同。在任何情况下,关键是你可以做出假设 - 它不是随机的 - 但如果你依赖于精确的枚举,那么使用数组可能是个更好的主意。

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:

甚至更糟糕的是duri在上面指出的,删除和替换键的值会进一步改变。观察当我删除bar并执行Object.bar =“foo”然后枚举时会发生什么:

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 (!!!)

更多相关文章

  1. 显示json数组中的所有项目
  2. 图表。js数据数组使用PHP, MySQL。如何从JSON数组定义数据源?
  3. Javascript对象
  4. JavaScript初探系列之面向对象
  5. 从两个数组生成JSON
  6. 将对象值传递给指令而不是任何其他数据变量
  7. 对象的属性也要加引号吗
  8. 在javascript中过滤对象对象(过滤还是减少?)
  9. JavaScript系列----面向对象的JavaScript(2)

随机推荐

  1. C ++中Accessor函数的特征
  2. 用C++实现最短路径之Dijkstra算法
  3. c#如何在程序中定义和使用自定义事件
  4. C中的time()函数怎么用?
  5. C语言中%d,%s,%x,%f,%.100的意义
  6. c语言是什么意思
  7. C#中常用的运算符有哪些
  8. c语言如何输出玫瑰花数?(代码示例)
  9. 指针常量与常量指针举例说明
  10. C#是什么,能做些什么?