[英]How to compare javascript objects of an array with other object
Bellow is polyline object 波纹是折线对象
var firstpolyline = new L.Polyline(myPointList, {
color: 'red',
weight: 5,
smoothFactor: 1
});
I have added this polyline object into an array 我已将此折线对象添加到数组中
var allpolylines = [];
allpolylines.push(firstpolyline);
Like this I have added more 5 polyline objects to this array. 像这样我在这个数组中添加了5个折线对象。
Now I am creating one more polyline object. 现在我正在创建另一个折线对象。
var mytpolyline = new L.Polyline(myPointList, {
color: 'red',
weight: 5,
smoothFactor: 1
});
now I want to compare mytpolyline object with objects of an array & find index of that array object. 现在我想比较mytpolyline对象与数组的对象并找到该数组对象的索引。
What I have tried is 我试过的是
var index = allpolylines.indexOf(mytpolyline);
but this is not giving index of array object. 但这不是给出数组对象的索引。
You cannot compare Objects directly, they never are equal, except you are explicitely referencing them 您无法直接比较对象,它们永远不会相等,除非您明确地引用它们
var a = {};
var b = {};
var c = a;
b == a // false
c == a // true
If you want to check if objects in your array are equal, unfortunately you have to compare each property individually. 如果要检查数组中的对象是否相等,很遗憾,您必须单独比较每个属性。
for (prop in a){
if (a.hasOwnProperty){
// compare a.prop to b.prop
}
}
With plain (non-object) properties and newer browser you could do this: 使用普通(非对象)属性和更新的浏览器,您可以这样做:
function comp(a,b){
return Object.keys(a).every(function(prop){
if (!b[prop]){ return false; }
else if (a[prop] !== b[prop]){ return false; }
return true;
});
}
See an example . 看一个例子 。
References: 参考文献:
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/every https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/every
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.