【问题标题】:Array.find is not a function errorArray.find 不是函数错误
【发布时间】:2018-06-22 16:20:08
【问题描述】:

我有一个值存储在名为 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"},
    ],
};

【问题讨论】:

  • 虽然从stations.js 导出了什么?
  • 好吧,Stations 并不是您认为的最有可能的情况。 console.log(Stations)
  • @epascarello - console.log(Stations) 返回包含上述数组的 JSON。
  • 因此,如果您的代码在返回的对象中,则必须引用 STATIONS
  • @epascarello - 像这样:let stationNewName = Stations.find((s) => STATIONS[s.stationName === myStation]);?

标签: javascript alexa-skills-kit


【解决方案1】:

您的导出包含一个具有一个属性的对象,该属性包含一个数组。因此,您需要引用对象的一个​​属性才能访问您认为正在引用的数组

let stationNewName = Stations.STATIONS.find((s) => s.stationName === myStation);

【讨论】:

  • 这消除了一个错误,但记录了“stationNewName = [object Object]”。因此,在我问的部分原始问题中,“当我找到匹配项时,我想获取 stationID”。我是否需要一个 if 语句,例如:if (Stations.STATIONS.find((s) => s.stationName === myStation)) { let stationNewName = s.stationID or Stations.STATIONS.stationID }
【解决方案2】:

使用 find 方法后,如果传递的谓词为真,则返回数组的元素,您需要引用成员 stationId,因为 STATIONS 数组中的每个元素都是一个对象。

'use strict';

module.exports = {
  STATIONS: [{
      stationName: "CBS",
      stationID: "8532885"
    },
    {
      stationName: "NBC",
      stationID: "8533935"
    },
    {
      stationName: "ABC",
      stationID: "8534048"
    },
  ],
};

// Import the default export from the stations.js module which is the object containing the STATIONS array.
const Stations = require("./stations.js");

const myStation = 'STATION_NAME';

// Find the first element within STATIONS with the matching stationName
const station = Stations.STATIONS.find((s) => s.stationName === myStation);

// As find will return the found element which is an object you need to reference the stationID member.
const stationId = station.stationID;

【讨论】:

    猜你喜欢
    • 2016-01-04
    • 1970-01-01
    • 1970-01-01
    • 2017-10-23
    • 2013-01-04
    • 1970-01-01
    • 2017-05-09
    • 2018-08-24
    • 1970-01-01
    相关资源
    最近更新 更多