javascript - js array.IndexOf 不能处理对象?

标签 javascript arrays object javascript-objects indexof

我正在尝试创建一个包含保存日期和时间的对象的数组。我正在遍历一个可能有重复的源,所以我想每次检查我是否还没有存储当前的日期和时间。

但是,我总是以重复结束。所以我认为 array.indexOf 可能不适用于对象?

    movies.forEach(function(movie){
        if (days.indexOf(movie.day) !== -1) { //if the movie's day exists in our array of available days...
            possibleMovies.push(movie);

            //create a day/time object for this movie
            dt = {day: movie.day, time: movie.time};

            //unless we already have this day and time stored away, do so
            if (possibleTimes.indexOf(dt) === -1) {
                possibleTimes.push(dt);
            }

        }
    });

循环完成后 possibleTimes 保持什么:

[ { day: '01', time: '18:00' },
  { day: '01', time: '16:00' },
  { day: '01', time: '18:00' },
  { day: '01', time: '16:00' } ]

我希望第三行和第四行不在那里......

------------ 更新------------

我变了

dt = {day: movie.day, time: movie.time};

进入这个

dt = JSON.stringify({day: movie.day, time: movie.time});

它按预期工作。检索数据后只需要 JSON.parse。

最佳答案

根据 MDN :

indexOf() compares searchElement to elements of the Array using strict equality (the same method used by the ===, or triple-equals, operator).

这就是为什么 possibleTimes.indexOf 总是导致 -1。

关于javascript - js array.IndexOf 不能处理对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35212947/

相关文章:

javascript - jQuery : Set both "key" and "value" using variance values

c - 声明一个未知大小的数组

javascript - 检查 JavaScript 中数组、对象、字符串和数字等数据类型的空值

xml 元素作为对象 HTMLCollection 返回

javascript - 使用 API V3 的主要谷歌地图故障

javascript - map 不是 map

java - 错误不兼容的类型。后缀评估

c# - 二维 javascript 数组到 c# 数据表?

javascript - ECMAScript/JavaScript 字符串中的每个字符消耗多少 RAM?

javascript - 在 C# 中以编程方式设置和获取浏览器窗口坐标值 (x,y)