如何比较两个Moment.js对象

Gab*_*Vip 0 javascript arrays comparison datetime momentjs

我有一个在变量中带有Moment.js对象的数组:

var feriados = function addFeriados(){
            feriados = [];
            ...
            feriados.push(moment("2016-01-01"));
            feriados.push(moment("2016-02-08"));
            feriados.push(moment("2016-02-09"));
            feriados.push(moment("2016-03-25"));
            feriados.push(moment("2016-04-21"));
            feriados.push(moment("2016-05-01"));
            feriados.push(moment("2016-05-26"));
            feriados.push(moment("2016-09-07"));
            feriados.push(moment("2016-10-12"));
            feriados.push(moment("2016-11-02"));
            feriados.push(moment("2016-11-15"));
            feriados.push(moment("2016-12-25"));
            ...
            return feriados;
 } 
Run Code Online (Sandbox Code Playgroud)

还有一个确定该数组中是否有值的函数:

function checkFeriado(data) {
    var i;
    for (i = 0; i < allFeriados.length; i++) {
        if (allFeriados[i] == data) {
        return true;
        }
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

但是,即使我传递了一个moment对象,因为checkFeriado(moment("2016-01-01"));我越来越虚假。我的代码有什么问题?有没有最好的方法可以做到这一点?

整个项目都有jQuery和Moment.js

sab*_*ker 8

moment("2016-01-01") !== moment("2016-01-01"); //true
//just like
{a:1} !== {a:1}; //true
Run Code Online (Sandbox Code Playgroud)

JavaScript对象不能像这样进行比较,同样有片刻的javascript对象。Moment拥有自己的实现来检查日期是否相等。使用是相同的

moment('2010-10-20').isSame('2010-10-20'); // true
moment('2010-10-20').isSame(moment('2010-10-20')); // true
Run Code Online (Sandbox Code Playgroud)

您也可以使用Array.filter进行检查。

我想知道您的意思fearadios = allFeradios()是在函数调用中吗?

allFeradios.length在您的示例中听起来不正确!因为它是一个函数名,所以feradios也是如此。

moment("2016-01-01") !== moment("2016-01-01"); //true
//just like
{a:1} !== {a:1}; //true
Run Code Online (Sandbox Code Playgroud)
moment('2010-10-20').isSame('2010-10-20'); // true
moment('2010-10-20').isSame(moment('2010-10-20')); // true
Run Code Online (Sandbox Code Playgroud)