我有一个对象列表,如下所示:
Object {title: "The Amaze - 2016-12-31 10:00", date: "10/12/2016", time: "10.00am"…}
Object {title: "The Amaze - 2016-12-31 12:00", date: "31/12/2016", time: "12.00am"…}
Object {title: "The Amaze - 2016-12-31 10:00", date: "31/12/2016", time: "10.00am"…}
我正在尝试遍历此object
列表,并且有一个条件语句,说明日期是否匹配,然后执行某些操作。
dateArray
是我的对象列表。可能是不好的做法,称其为名称中的数组但是......
for (var j = 0; j < dateArray.length; j++) {
if (dateArray[j].date === sDate) {
if (dateArray[j].date === dateArray[j].date) {
console.log(dateArray[j], "<<<<< Matched");
}
}
}
任何人都可以解释我是如何实现我想要做的。
此外,sDate
只是一个变量,我在顶部显示了当前日期。
答案 0 :(得分:0)
试试这个会检查你可以改变循环条件的每个组合
for (var j = 0; j < dateArray.length; j++)
{
for (var k =0 ; k < dateArray.length; k++)
{
if(k==j)
{
continue; // this is same object
}
else
{
if (dateArray[j].date === dateArray[k].date) {
console.log(dateArray[j], "<<<<< Matched");
}
}
}
答案 1 :(得分:0)
您可以使用对象和单个循环。该对象作为日期的哈希表,如果存在,则找到匹配。
var array = [{ title: "The Amaze - 2016-12-31 10:00", date: "10/12/2016", time: "10.00am" }, { title: "The Amaze - 2016-12-31 12:00", date: "31/12/2016", time: "12.00am" }, { title: "The Amaze - 2016-12-31 10:00", date: "31/12/2016", time: "10.00am" }];
array.forEach(function (a, i) {
if (this[a.date]) {
console.log('match @ ' + i);
}
this[a.date] = true;
}, Object.create(null));
&#13;
保留日期索引的提案
var array = [{ title: "The Amaze - 2016-12-31 10:00", date: "10/12/2016", time: "10.00am" }, { title: "The Amaze - 2016-12-31 12:00", date: "31/12/2016", time: "12.00am" }, { title: "The Amaze - 2016-12-31 10:00", date: "31/12/2016", time: "10.00am" }];
array.forEach(function (a, i) {
if (this[a.date]) {
console.log('match @ ' + i + ' with ' + this[a.date]);
}
this[a.date] = this[a.date] || [];
this[a.date].push(i);
}, Object.create(null));
&#13;