javascript - Array.find 不是函数错误
问题描述
我有一个值存储在一个名为 myStation 的变量中。现在我想在另一个名为 station.js 的文件中的数组中找到该值。当我找到匹配项时,我想获取 stationID。我正在使用的代码let stationNewName = Stations.find((s) => s.stationName === myStation);
导致错误“错误处理:Stations.find 不是函数”。我错过了什么?
我希望不必加载 Lodash 库的开销,并认为我应该能够使用基本的 javascript 代码来完成。以下是与错误相关的代码摘录:
需要 station.js 文件
const Stations = require("./stations.js");
这是导致错误的代码的摘录。下一行在我的一个处理程序中执行,其中 myStation 接收值“CBS”
const myStation = handlerInput.requestEnvelope.request.intent.slots.stationName.value;
下一行产生错误:“错误处理:Stations.find 不是函数”。
let stationNewName = Stations.find((s) => s.stationName === myStation);
这是我在stations.js 文件中的数组的摘录
STATIONS: [
{stationName: "CBS", stationID: "8532885"},
{stationName: "NBC", stationID: "8533935"},
{stationName: "ABC", stationID: "8534048"},
],
更新数组以包含完整模块
'use strict';
module.exports = {
STATIONS: [
{stationName: "CBS", stationID: "8532885"},
{stationName: "NBC", stationID: "8533935"},
{stationName: "ABC", stationID: "8534048"},
],
};
解决方案
您的导出包含一个具有一个属性的对象,该属性包含一个数组。因此,您需要引用对象的一个属性才能访问您认为正在引用的数组
let stationNewName = Stations.STATIONS.find((s) => s.stationName === myStation);
推荐阅读
- node.js - 如何使用 npm 脚本重命名文件
- java - 在改造之外打印时值为空的数组列表
- java - 如何使用 Jsoup 从网页中获取特定 div 内的所有链接?
- android - 房间更新多个字段
- html - 为什么 flexbox 中的强文本表现为列?
- docker - 从外部安全地访问 docker 容器而不暴露它
- angular - 在 mat-calendar 中突出显示某些日期
- c# - 如何修复 Visual Studio 构建错误:[MSB3248:参数“SearchPaths”具有无效值]?
- javascript - 如何正确遍历数组并使用范围
- mysql - 计算给定日期范围内每个月的平均值