简体   繁体   English

JavaScript错误:无法读取未定义的属性“包含”

[英]JavaScript error: Cannot read property 'includes' of undefined

I want to check if a data.objectId already exists in the array msgArr . 我想检查数组msgArr data.objectId已存在msgArr For that I am running the code below: 为此我运行下面的代码:

var exists = msgArr.objectId.includes(data.objectId);

if(exists === false){
   msgArr.push({"objectId":data.objectId,"latLont":data.latLont,"isOnline":data.isOnline});
}

The array looks like the following: 该数组如下所示:

var msgArr = [
  {isOnline:true,latLont:"123",objectId:"on0V04v0Y9"},
  {isOnline:true,latLont:"1",objectId:"FpWBmpo0RY"},
  {isOnline:true,latLont:"48343",objectId:"Qt6CRXQuqE"} 
 ]

I am getting the error below: 我收到以下错误:

Cannot read property 'includes' of undefined 无法读取未定义的属性“包含”

As the comments say: the javascript array object has no property objectId . 正如评论所说:javascript数组对象没有属性objectId
Looking at the objects in this array it's clear that they have it, so to check if a certain element exists you can do so using Array.prototype.some method: 查看此数组中的对象,很明显他们拥有它,因此要检查某个元素是否存在,您可以使用Array.prototype.some方法执行此操作:

var exists = msgArr.some(o => o.objectId === data.objectId);

It's telling you that you're trying to access a property on an undefined object. 它告诉您,您正在尝试访问未定义对象上的属性。 The msgArr object doesn't have a property objectID at all, which means it's undefined . msgArr对象根本没有属性objectID ,这意味着它是未定义的 Since that doesn't exist, there's no way for it to have an includes property available of any type. 由于这不存在,因此无法使用任何类型的includes属性。

What you need is to access an object in the array, not the array itself. 您需要的是访问数组中的对象,而不是数组本身。 Something like msgArr[0].objectID would refer to an instantiated object. msgArr[0].objectID这样的东西会引用一个实例化的对象。 You could even use the array functions to check if something exists based on its objectID with a filter function. 您甚至可以使用数组函数根据其带有过滤器函数的objectID来检查是否存在某些内容。

First of all Dave Newton is right. 首先戴夫牛顿是对的。 An array doesn't have an objectId! 数组没有objectId!

Maybe your "array" isn't a real array. 也许你的“数组”不是真正的数组。 Maybe it's an object which contains an array... I don't know... but in that case, you would have to code something like this: 也许它是一个包含数组的对象...我不知道......但在这种情况下,你必须编写类似这样的代码:

var exist = msArr["objectId"] !== undefined

than "exist" which is a boolean contains the info if "msArr" has an property/field called "objectId" 如果“msArr”具有名为“objectId”的属性/字段,则“存在”是布尔值,其中包含信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM