javascript - NodeJs 堆 js 模块 : Heap is not a constructor

标签 javascript node.js data-structures module heap

我正在尝试使用 head-js 模块 ( https://github.com/ignlg/heap-js ) 在我的 server.js 中初始化最小堆/优先级队列。当我运行我的代码时,我收到以下错误:

var minHeap = new Heap(customComparator);

TypeError: Heap is not a constructor

但是,根据文档,我正确地初始化了堆,将自定义构造函数作为参数放入。下面是我的代码:

var Heap = require("heap-js");
// Build a minimum heap of size k containing the k cities with the most active users
var customComparator = (city1, city2) => citySizes[city1] - citySizes[city2];
var minHeap = new Heap(customComparator);

最佳答案

CommonJSES6 模块 中使用 heap-js 库是有区别的。

requireing(即 CommonJS)时,您需要从返回的对象中析构出 Heap 类,如下所示:

const { Heap } = require('heap-js') // correct
const Heap = require('heap-js') // incorrect

然而,在 ES6 中你必须做相反的事情,如下所示:

import Heap from 'heap-js' // correct
import { Heap } from 'heap-js' // incorrect

关于javascript - NodeJs 堆 js 模块 : Heap is not a constructor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57950779/

相关文章:

javascript - node.js 中的子/辅助线程

macos - Bower 安装错误

C 创建有序优先级队列

c++ - 在线区间并集的长度

c - 交换链表中的节点

javascript - 如何使用 jQuery/javascript 将事件处理限制为每 X 秒一次?

javascript - 具有多种形状/元素的剪贴蒙版设计

javascript - IE 11 的 Map(iterable) 替代方案

node.js - 找不到名称 "module"

javascript - 尽管文件存在,但获取 'Module not found'