Immutable.js中Map.entrySeq的遍历顺序是否可信赖?
Absolutely, you can fully trust this order—here's why:
First, let's clarify a core feature of Immutable.js's Map: unlike some older hash map implementations, it's explicitly designed to preserve insertion order for keys. This behavior is intentional and part of the library's API contract, not an accidental side effect.
In your code:
const myMap = [array with keys].reduce((acc, key) => acc.set(key, 1), Map());
You're iterating over your key array in a fixed sequence, calling set() to add each key to the Immutable Map one by one. Each set() call for a new key appends it to the map's internal ordered collection of entries.
When you call entrySeq(), it returns a sequence of key-value pairs that strictly follows the order in which keys were first inserted into the map. This means the output of entrySeq() will match exactly the order your reduce loop executed those set() calls (which is the same as the order of keys in your original array).
A quick example to confirm:
import { Map } from 'immutable'; const keys = ['zebra', 'apple', 'banana']; const fruitMap = keys.reduce((acc, key) => acc.set(key, 1), Map()); // Logs the entries in the same order as the keys array console.log(fruitMap.entrySeq().toArray()); // Output: [ ['zebra', 1], ['apple', 1], ['banana', 1] ]
One small note: if you later update an existing key (using set() on a key that's already in the map), this won't change its position in the entry sequence—only new keys get added to the end of the order.
To wrap up: this order is not just a coincidence. It's a guaranteed behavior of Immutable.js's Map and entrySeq() method, so you can rely on it in your code without worry.
内容的提问来源于stack exchange,提问作者kit

