问题
I'm trying to find the index of my object inside an array in Javascript.
This is the code I'm using, this returns -1 so it's not found. But it's there
var index = this.state.users.indexOf(user);
The object I'm comparing with is identical to the one's in the collection as shown in the picture below
I'm using this code to compare the two
console.log(this.state.users[0]);
console.log(member);
So I don't understand why this is giving a negative result
回答1:
In javascript object compared by reference, such as
var obj1 = {prop: 0};
var obj2 = {prop: 0};
alert(obj1 === obj2); //false
indexOf
compare like this, so it isn't finding anything.
To find object in array identical to given, you can use Array.prototype.filter method.
Or ecmascript 2015 Array.prototype.find method
回答2:
Array indexOf uses STRICT EQUALITY (===)
so
var v1 = {id:1, info:{something:'else'}};
var v2 = {id:2, info:{something:'else'}};
var v3 = {id:1, info:{something:'else'}};
var v4 = v2;
var arr = [v1, v2];
arr.indexOf(v2); // 1
arr.indexOf(v3); // -1
arr.indexOf(v4); // 1
even though v3 looks just like v1, it's not v1
so it depends on how the object you are trying to find is related to the objects in the array
回答3:
IndexOf function is used to find an occurrence of a string in another one.
When this occurrence is not found, the function return -1.
Please refer to this website for more informations :
http://www.w3schools.com/jsref/jsref_indexof.asp
回答4:
It returns -1 if it never occurs.
http://www.w3schools.com/jsref/jsref_indexof.asp
回答5:
It uses strict comparison to find member in the users array.
What it means is that if it will return -1
if for every entry in your array member !== theUserYouAreLookingFor
(which is the case when variables are not holding reference to the same object, not similar but the same object in memory).
回答6:
You need a custom function for something like this, in which you pass the array you want to search in, the object you want to find the index for and a unique property of the object:
var indexOfArrayObject = function(arr, obj, prop) {
var index = -1;
arr.some(function(val, ind){
if(val[prop] === obj[prop]) {
index = ind;
return true;
}
});
return index;
}
// Getting the index by 'id'
var userIndex = indexOfArrayObject(this.state.users, user, 'id');
回答7:
Because, in JavaScript, { a: 1 } === { a: 1 }
or { a: 1 } == { a: 1 }
is false.
In your environment, you'll also find that this.state.users[0] === member
is false too.
So, the method you're using for comparison is not correct.
来源:https://stackoverflow.com/questions/31831599/javascript-indexof-object-not-found