Twi*_*ist 4 javascript ecmascript-5 ecmascript-6
例如:片段 img
var a = {1: '1', 2: '2'}
var b = {3: '3', 4: '4'}
Object.assign({}, a, b)
> {1: "1", 2: "2", 3: "3", 4: "4"}
Object.assign({}, b, a)
> {1: "1", 2: "2", 3: "3", 4: "4"}
Run Code Online (Sandbox Code Playgroud)
有没有办法禁用排序?
不,因为(如您所说)数字键(或使用规范的术语,整数索引*)。
Object.assign按 定义的顺序工作[[OwnPropertyKeys]],对于普通对象是OrdinaryOwnPropertyKeys抽象操作,它按定义的顺序列出属性(首先是整数索引,然后是其他字符串命名的属性,然后是创建顺序,然后是符号命名的属性) . 结果对象的属性将以相同的方式枚举(通过遵循定义顺序的操作),因此,整数索引,数字,然后是其他属性,按照创建顺序。
如果您的键不是整数索引,您可以通过按照您想要的顺序预先创建属性来控制结果的顺序,但不是在整数索引键的情况下。
因此,例如,如果您的键是a, b, c, 和d,您可以确定结果对象的属性列出的顺序(对于遵循顺序的操作):
const x = {a: 'a', b: 'b'};
const y = {c: 'c', d: 'd'};
const result1 = Object.assign({c: null, d: null, a: null, b: null}, x, y);
console.log(JSON.stringify(result1));
const result2 = Object.assign({c: null, d: null, a: null, b: null}, y, x);
console.log(JSON.stringify(result2));
const result3 = Object.assign({a: null, b: null, c: null, d: null}, x, y);
console.log(JSON.stringify(result3));
const result4 = Object.assign({a: null, b: null, c: null, d: null}, y, x);
console.log(JSON.stringify(result4));Run Code Online (Sandbox Code Playgroud)
请注意,我使用JSON.stringify那里的输出,因为JSON.stringify被定义为跟随产权制度(而for-in并Object.keys没有)。
但不适用于您的键,它们是整数索引。
如果顺序很重要,通常一个对象是错误的数据结构;相反,您需要一个数组。数组也是对象,数组的一些有序性只是约定俗成的(优化除外),但它们具有几个重要的特定于顺序的特性,尤其是length属性及其以定义的顺序工作的各种方法。
一个整数指数是一个字符串值属性密钥是一个规范的数字串(见7.1.16),并且其数字值是0或正整数?2 53 -1。
| 归档时间: |
|
| 查看次数: |
1229 次 |
| 最近记录: |