javascript - ImmutableJS 会跳过未使用的代码块吗?

标签 javascript immutable.js

我正在研究 Immutable.js 代码,发现了一些奇怪的东西。 Immutable.js 会跳过保存到不会使用的变量的代码吗?

const Immutable = require('immutable')

function transformErrors(errors) {
    let key = errors.keySeq()
    let mapped = key.map((v, keystr) => {
      console.log(v, keystr)
      return keystr
    })
  // If I enable the console log below, console log above works
  // console.log('mapped', mapped) 
};
const result = transformErrors(Immutable.fromJS([1, 2]));

对于上面的代码,如果

console.log('mapped', mapped)

被禁用,映射代码不会被调用。 我查看了文档,但找不到任何关于它的评论

最佳答案

行:let key = errors.keySeq() 将返回一个 Seq 对象,这在 immutable.js 中是惰性的。

文档提供了以下详细信息 ( https://facebook.github.io/immutable-js/docs/#/Seq ):

Seq is lazy — Seq does as little work as necessary to respond to any method call. Values are often created during iteration, including implicit iteration when reducing or converting to a concrete data structure such as a List or JavaScript Array. For example, the following performs no work, because the resulting Seq's values are never iterated:

const { Seq } = require('immutable')
const oddSquares = Seq([ 1, 2, 3, 4, 5, 6, 7, 8 ])
  .filter(x => x % 2 !== 0)
  .map(x => x * x)

因此在您的示例中,immutable.js 不会实际评估您的 map 函数,直到在某处使用了 mapped

关于javascript - ImmutableJS 会跳过未使用的代码块吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46125752/

相关文章:

javascript - 创建复杂的 SVG,无需中间字符串

JavaScript:以 mm/dd/yyyy 格式拆分和连接日期

javascript - 如何将选项从 PHP 传递到 Javascript?

c# - 描述 bool 值的 json

reactjs - 优化更新 redux 状态

out-of-memory - 基于不可变数据结构的应用程序不会耗尽内存吗?

javascript - Immutablejs - 更新嵌套映射和列表中的值

javascript - 从 li 的子节点检索文本

javascript - 如何仅显示项目 map (如果存在)

javascript - 如何构造 Immutable.Record 的子类?