Array.find不是函数错误

时间:2018-06-21 16:08:46

标签: javascript alexa-skills-kit

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

2 个答案:

答案 0 :(得分:2)

您的导出包含一个对象,该对象的一个​​属性包含一个数组。因此,您需要引用该对象的一个​​属性,以获取您认为要引用的数组

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

答案 1 :(得分:0)

使用find方法(如果传递的谓词为true时将返回数组的元素)后,您需要引用成员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;

相关问题