【问题标题】:Can not read property of array element in javascript无法在javascript中读取数组元素的属性
【发布时间】:2019-07-16 07:30:45
【问题描述】:

我对 javascript 相当陌生,我试图找到由 configID 属性创建的数组的对象。我为此使用了find()的方法。

JS 代码:

var configurationArray = flow.get("configurationArray") || [];
var configurationId = msg.topic.split("/")[1];
var configuration = {
  configID: this.configurationID,
  configurationModules: this.MSGesture.payload
};

if(!configurationArray.find(x => x.configID == this, configurationId)){
  configurationArray.push(this.configuration);
} else {
  //to do
}

我正在使用 node-red,它给了我 flowmsg

我得到的错误:

Cannot read property 'configId' of undefined

感谢任何帮助

【问题讨论】:

  • 错误明确指出x 的值未定义,只需将其更改为x && x.configId
  • 同时检查是否定义了变量及其长度if (configurationArray && !!configurationArray.length && configurationArray.find(...) )
  • @CodeManiac 你的回答也有效,谢谢。

标签: javascript arrays node-red


【解决方案1】:

您可以解构该属性并添加一个默认对象。

然后使用some 而不是find,因为您只需要支票。

最后,省略this,直接取值。

if (!configurationArray.some(({ configID } = {}) => configID === configurationId)) {
    configurationArray.push(this.configuration);
} else {
    //to do
}

如果你喜欢抽象回调,你可以对configurationId 进行闭包,比如

const hasId = id => ({ configID } = {}) => configID === id;

if (!configurationArray.some(hasId(configurationId)) {
    configurationArray.push(this.configuration);
} else {
    //to do
}

【讨论】:

  • 这行得通。谢谢!您能否解释一下({ configID } = {}) 的作用?我不完全明白它在=> 前面做了什么。
  • 这是一个destructuring assignment 和一个default parameters。它接受一个对象,或者如果值为undefined,则默认对象并从对象中拉出configID
猜你喜欢
  • 2019-08-02
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 2014-09-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多