javascript - 为什么在将对象插入数组后 indexOf 不起作用

标签 javascript arrays indexof

我试图在将 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 .所以在这种情况下,对 objarr[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/

相关文章:

javascript - 如何在智能电视浏览器上对我的网站进行故障排除?

javascript - 即使在 href 重定向之后如何使用 setTimeout 循环?

c++ - 错误 C2059 : syntax error : ']' , 我无法弄清楚为什么这会出现在 C++ 中

java - 字符串数组中的 indexOf

c# - 什么是 href ="javascript:__doPostBack(' ctl00$cph1$mnuPager' ,'b3' )">

javascript - 在函数中间注入(inject)值

javascript - 使用外部数据输入更新数组中的对象时提高性能

c++ - 在 C++ 中调用的第二个构造函数(错误输出)

python - 使用 Python 在字符串列表中查找项目的索引

c# Array.FindAllIndexOf 其中 FindAll IndexOf