简体   繁体   English

在Immutable.js Map()数据结构中使用first()方法

[英]using the first() method in Immutable.js Map() data structure

The Map data structure in Immutable.js has a first() method. Immutable.js中的Map数据结构具有first()方法。

As my understanding goes, Maps are unordered. 据我了解,地图是无序的。 How is it then the first() method always returns the same item ? 那么first()方法如何总是返回相同的项目呢?

  it('should return the value of the fist item in data structure', ()=> {
    var x = Immutable.Map({a: 10, b: 20, c: 30});
    expect(x.first()).to.equal(10); //passess everytime

  });

It's just a byproduct of implementation that you're not allowed to rely on (and is probably at least partially browser-dependent, thanks to the object initializer you're using 1 ). 它只是实现的副产品,您不能依赖它(并且可能至少部分依赖于浏览器,这要归功于您使用的对象初始化器1 )。 As it says in the documentation : 文档所述

Iteration order of a Map is undefined, however is stable. Map的迭代顺序是不确定的,但是是稳定的。

So the order is undefined, and could change from one dot rev to the next. 因此顺序是不确定的,并且可以从一个点转速更改为下一个。 But the same code, repeated, is going to have the same outcome. 但是,重复相同的代码将具有相同的结果。 Computers are deterministic. 计算机是确定性的。


1 Until ES2015, JavaScript objects didn't officially have an order to their properties. 1直到ES2015,JavaScript对象才正式对其属性进行排序。 As of ES2015, they do, but that order is only guaranteed to be followed by some operations. 从ES2015开始,它们会执行此操作,但是只能保证某些操作遵循该顺序。 Notably, neither for-in nor Object.keys are required by the spec to follow the order. 值得注意的是,规范不需要for-inObject.keys都可以遵循该顺序。 So since building the map will require iterating the object you're passing in, it's possible the result you see (which is undefined) will vary from JavaScript engine to JavaScript engine. 因此,由于构建地图将需要迭代您传入的对象,因此您看到的结果(未定义)可能会因JavaScript引擎而异。 That said, even before the spec, most engines handled properties at the same level in the object hierarchy in the same way (order of property creation, if we ignore property names that qualify as array indexes; and the properties of an object initializer are added to the object in source-code order [even in ES5]). 就是说,即使在规范之前,大多数引擎仍以相同的方式在对象层次结构中的同一级别处理属性(属性创建的顺序,如果我们忽略符合数组索引条件的属性名称;并且添加了对象初始化程序的属性以源代码顺序添加到对象[即使在ES5中也是如此]。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM