我正在尝试创建一个包含保存日期和时间的对象的数组。我正在遍历一个可能有重复的源,所以我想每次检查我是否还没有存储当前的日期和时间。
但是,我总是以重复结束。所以我认为 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/