使用superheroes npm包时遇TypeError: superheroes.random不是函数
解决superheroes包
random()方法无法调用的问题 问题出在superheroes包的API版本更新上:旧版本(v3.x及以下)提供random()便捷方法,但v4.x及以上的新版本已经移除了这个方法,只保留了all属性(包含所有超级英雄名称的数组)。
解决方案
直接从superheroes.all数组中随机选取元素,自己实现随机逻辑即可,代码修改如下:
import superheroes from "superheroes"; // 计算随机索引并获取对应英雄名称 const randomHeroName = superheroes.all[Math.floor(Math.random() * superheroes.all.length)]; console.log(`I am ${randomHeroName}!`);
补充说明
- 你之前添加
"type": "module"到package.json的操作是正确的,已经解决了模块类型警告。 - 重新安装包后默认会拉取最新版本,这就是为什么你找不到
random()方法的原因,并非使用方式错误或包存在bug。
内容的提问来源于stack exchange,提问作者Soon Winner
相关产品推荐
相关产品推荐

