是否保证JavaScript数组顺序? [英] Is a JavaScript array order guaranteed?

查看:91
本文介绍了是否保证JavaScript数组顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设一个JavaScript数组在表单中发布(使用ajax / JQuery)
是保证数组中的顺序吗?

Assuming a JavaScript array is posted in a form (using ajax/JQuery) is the order in the array guaranteed?

来自@Quentin的有效问题
定义以表格形式发布'

Valid question from @Quentin "Define 'posted in a form'"

$.ajax({
  type: "POST",
  url: url,
  data: { foo: [{ name: "one" }, { name: "two" }] },
  success: success,
  dataType: dataType
});

扩展问题(由于上述原因),
阵列保证保留服务器端的订单?

Expanding on the question (because of the above), Is the array guaranteed to preserve the order on the server side?

推荐答案

怀疑时你总是可以参考ECMAScript标准:数组外来对象

You can always refer to the ECMAScript standard when in doubts: Array Exotic Objects

Array是一种特殊类型的对象,在语言中对于从0到2 ^ 32的整数属性处理长度属性的方式有额外的语义。在javascript中,如果缺少0到length属性的缺失值,则数组可以是稀疏的。各种数组方法都考虑到了这一点,例如 forEach 忽略缺失值

Array is a special kind of object in the language that have additional semantic on how length property is handled respect to the properties that are integers from 0 to 2^32. In javascript an array can be sparse if there are missing values in the range of 0 to the length property excluded. Various array methods take this in consideration, for example forEach ignore missing values

什么是缺失值?

语言尝试使数组充当与普通对象一样多:你可以向它添加任何属性,甚至还有从数组继承的对象。

The language tries to make arrays act as much as possible as to normal objects: you can add any property to it and even have objects that inherit from an array.

var fruits = ["Apple", "Banana"];
fruits.preferred = "Apple";

这种代码不会造成任何问题,但如果你开始写:

This kind of code don't pose any problem, but if you start to write:

fruits[100] = "Strawberry";
for(let i = 0; i < fruits.length; ++i) {
...
}

100是[0,2 ^ 32]范围内的属性名称,因此是一个数组元素,但此时应该是fruits.length吗?它必须是101,否则for循环永远不会得到草莓。

100 is a property name in the range of [0, 2^32) so is an array element but at this point what fruits.length should be? It must be 101, otherwise the for loop will never get "Strawberry".

但此时你必须接受有一系列元素[2,99] ]从未定义:这些是缺失值。

But at this point you have to accept that there is a range of element [2, 99] that were never defined: these are missing values.

反之亦然,修改长度属性时必须如此

Vice versa the same must be true when you modify the length property

var fruits = ["Apple", "Banana"];
fruits.length = 0;

现在for循环永远不会获得数组的任何元素:这相当于清空fruits数组。

Now a for loop will never get any element of the array: this is equivalent to emptying the fruits array.

也可以增加长度,结果是缺少值

It's also possible to increment the length, with the result of having missing values

所以是数组是有序,因为你可以按递增的顺序迭代它的所有元素,但要记住可能有缺失的值

So yes arrays are ordered as you can iterate all its elements in increasing order, but keep in mind that there can be missing values

这篇关于是否保证JavaScript数组顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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