var myWidth = 20;
var myHeight = 30;
allDims = [
{w: 20, h: 30},
{w: 10, h: 15}
]
if ($.inArray({w: myWidth, h: myHeight}, allDims) !== -1) {
...
}
Why is the if-condition always returning -1?
var myWidth = 20;
var myHeight = 30;
allDims = [
{w: 20, h: 30},
{w: 10, h: 15}
]
if ($.inArray({w: myWidth, h: myHeight}, allDims) !== -1) {
...
}
Why is the if-condition always returning -1?
This doesn't work because the equality test on objects is based on the equality of references.
From the MDN :
Two distinct objects are never equal for either strictly or abstract comparisons
So you must implement the index search yourself, by looping and comparing both w and h.
For example :
var index = -1;
for (var i=0; i<allDims.length; i++) {
if (allDims[i].w==myWidth && allDims[i].h==myHeight) {
index = i;
break;
}
}
If you want something more elegant, you could use filter and pass a function, but it would iterate over the whole array even when not needed. A generic function similar to indexOf but taking a callback to check equality can be designed :
Array.prototype.indexFunc = function(o, equal) {
for (var i=0; i<this.length; i++) {
if (equal(o,this[i])) return i;
}
return -1;
}
console.log(allDims.indexFunc({w:10, h:15}, function(a,b) {
return a.w==b.w && a.h==b.h
})); // logs 1