【问题标题】:Why doesn't indexOf work after pushing object in array为什么在数组中推送对象后 indexOf 不起作用
【发布时间】:2017-08-03 19:02:25
【问题描述】:

我试图在将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 arrays indexof


【解决方案1】:

问题在于 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' });

【讨论】:

  • 我编辑了我的代码,你能用那个举例说明吗?为什么我不明白! -1
  • 每次运行函数时,对path 的引用都会发生变化,因为每次运行函数时都要重新定义path。在定义 setTimeout 调用之前,您必须保存 path
  • 是不是因为我使用 setInterval 和 forEach() 来获取路径?
  • 好吧,我在您的代码中的任何地方都看不到forEach,但setInterval 是。每次你调用这个函数时,里面的一切基本上都是第一次。当函数在运行之间结束时,函数的内部范围(内存)将丢失。
  • 我添加了两个应该对您有所帮助的新示例。
【解决方案2】:

第一次执行 indexOf 时,您推送并搜索对象“路径”,以便找到它。第二次创建一个对象并将其添加到数组中,然后搜索另一个新对象(恰好具有相同的值),但由于它与您推送的对象不同,因此未找到。

【讨论】:

    猜你喜欢
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 2015-01-04
    • 2012-04-16
    相关资源
    最近更新 更多