为什么删除任何键时不可变映射顺序会更改?

Why Immutable Map Order Changed When Any Keys Deleted?

我在 React 应用程序上使用 Immutable JS 和 Redux 时遇到问题。这是我创建的示例代码:

const entry1 = {id: 1, name: 'Entry 1'}
const entry2 = {id: 2, name: 'Entry 2'}
const entry3 = {id: 3, name: 'Entry 3'}
const entry4 = {id: 4, name: 'Entry 4'}
const entry5 = {id: 5, name: 'Entry 5'}

const entries = Immutable.Map({1: entry1, 2: entry2, 3: entry3, 4: entry4, 5: entry5})
const updatedEntries = entries.delete('3')

// First Console Log
console.log(entries.valueSeq().toJS())

// Second Console Log
console.log(updatedEntries.valueSeq().toJS())

在我的第一个控制台日志中,顺序是正确的:1,2,3,4,5。但是在我的第二个控制台日志中,顺序是乱七八糟的,它变成了:1,2,5,4.

知道我的代码有什么问题吗?

Map 不保证顺序。如果你想保持相同的顺序,你应该使用 OrderedMap

OrderedMap

A type of Map that has the additional guarantee that the iteration order of entries will be the order in which they were set()