js array.IndexOf 不处理对象?

js array.IndexOf not working with objects?

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

但是,我总是以重复结尾。所以我认为 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);
            }

        }
    });

循环完成后可能的时间:

[ { 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。

如果两个对象指向相同的位置,则它们被视为相等。

var obj1 = { x: 100 };
var obj2 = obj1;
console.log( obj1===obj2 );     //  outputs true

var obj1 = { x: 100 };
var obj2 = { x: 100 };
console.log( obj1===obj2 );     //  outputs false

您可以使用 JSON.stringify 将每个对象转换为字符串,然后进行比较。请记住,属性的顺序必须匹配。

console.log( JSON.stringify( obj1 ) === JSON.stringify( obj2) );    //outputs true

如果您愿意使用 Ramda,它会变得超级简单:

let a = [
  { day: '01', time: '18:00' },
  { day: '01', time: '16:00' },
  { day: '01', time: '18:00' },
  { day: '01', time: '16:00' }
];

let b = R.uniq(a);
console.log(b);

http://jsbin.com/ligihexate/edit?js,console