【问题标题】:NodeJs heap-js module: Heap is not a constructorNodeJs heap-js 模块:Heap 不是构造函数
【发布时间】:2019-09-16 05:21:20
【问题描述】:

我正在尝试使用 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);

【问题讨论】:

  • var {Heap} = require("heap-js"); 忘了解构

标签: javascript node.js data-structures module heap


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-24
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 2023-01-16
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    相关资源
    最近更新 更多