如果对象有数字键,在Object.assign中禁用排序的任何现代方法?

问题描述 投票:3回答:1

例如:snippet 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"}

有没有办法禁用排序?

javascript ecmascript-6 ecmascript-5
1个回答
2
投票

不,因为(如你所说)的数字键(或使用规范的术语,整数索引*)。

Object.assign按照[[OwnPropertyKeys]]定义的顺序工作,对于普通对象是OrdinaryOwnPropertyKeys抽象操作,它以定义的顺序列出属性(首先是整数索引,然后按创建的顺序列出其他字符串命名的属性,然后按顺序列出符号命名属性)创作)。生成的对象的属性将以相同的方式枚举(通过遵循定义的顺序的操作),因此,整数索引,数字,然后是creationg顺序中的其他属性。

如果您的键不是整数索引,则可以通过按照所需顺序预先创建属性来控制结果的顺序,但不能在整数索引键的情况下。

因此,例如,如果您的密钥是abcd,您可以确定列出结果对象属性的顺序(对于遵循该顺序的操作):

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

请注意,我在那里使用JSON.stringify作为输出,因为JSON.stringify被定义为遵循属性顺序(而for-inObject.keys不是)。

但不是你的键,它是整数索引。

如果顺序很重要,通常对象是错误的数据结构;相反,你想要一个数组。数组也是对象,数组的一些有序性只是约定(禁止优化),但它们有几个重要的特定于顺序的特性,尤其是length属性及其以定义的顺序工作的各种方法。


*“整数索引”定义为here

整数索引是一个字符串值属性键,它是一个规范数字字符串(见7.1.16),其数值为+0或正整数≤253-1。

© www.soinside.com 2019 - 2024. All rights reserved.