我正在尝试使用 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);
最佳答案
在 CommonJS 和 ES6 模块 中使用 heap-js
库是有区别的。
当 require
ing(即 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/