我试图在将 object
插入数组后获取 indexOf
。
这不会像我在数组中准备好 objext 时返回与 indexOf
相同的值。
场景
var arr = [];
setInterval(function() {
var path = { one: "f00"};
if (typeof path !== "undefined") {
if (arr.indexOf(path) === -1) {
console.log("Not Exists!!")
arr.push(path)
} else {
console.log("Exists!!")
}
}
console.log(arr)
}, 2000)
工作之间有什么不同
最佳答案
问题在于 JavaScript 不会对对象进行深入比较,因此它不会将它们识别为相同。
var a = { name: 'foo' }
var b = { name: 'foo' }
a === b // false
但是,由于您可以在插入之前访问对象,因此可以保存对它的引用,然后搜索该引用:
var arr = []
var obj = { path: 'foo' }
arr.push(obj)
arr.indexOf(obj) // 0
这是因为indexOf
使用 strict equality ===
comparison .所以在这种情况下,对 obj
和 arr[0]
处的对象的引用是相同的。
编辑
根据您更改的问题,这是一种编写函数来执行您想要的操作的方法:
var arr = [];
function findAdnSet(obj) {
var index = arr.indexOf(obj);
if (index !== -1) {
return index;
} else {
arr.push(obj);
return arr.length - 1; // No reason to use indexOf here, you know the location since you pushed it, meaning it HAS to be the last element in the array
}
}
var path = { name: 'foo' };
findAndSet(path);
比使用 indexOf
更可靠的选择是使用 find
,因为您的函数可能并不总是有可用的良好引用。/findIndex
:
var arr = [];
function findAndSet(obj) {
var index = arr.findIndex(function(item) {
if (item.name === 'foo') {
return true;
}
});
if (index) { // findIndex returns `undefined` if nothing is found, not -1
return index;
} else {
arr.push(obj);
return arr.length - 1;
}
}
// You don't need a reference anymore since our method is doing a "deep" compare of the objects
findAndSet({ name: 'foo' });
关于javascript - 为什么在将对象插入数组后 indexOf 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42769125/