I have an Array with Moment.js objects in a variable:
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;
}
And a function to determinate if a value is in this array:
function checkFeriado(data) {
var i;
for (i = 0; i < allFeriados.length; i++) {
if (allFeriados[i] == data) {
return true;
}
}
return false;
}
But even if i pass a moment
object, as checkFeriado(moment("2016-01-01"));
i'm getting false. Whats wrong with my code? Is there a best way to do this?
Entire project have jQuery and Moment.js
moment("2016-01-01") !== moment("2016-01-01"); //true
//just like
{a:1} !== {a:1}; //true
Javascript objects cannot be compared like this , same with moment's javascript objects . Moment has its own implementation to check if dates are equal. use isSame
moment('2010-10-20').isSame('2010-10-20'); // true
moment('2010-10-20').isSame(moment('2010-10-20')); // true
You can also use Array.filter to check this.
I wonder if you meant fearadios = allFeradios()
as in a function call?
allFeradios.length
doesn't sound right in your example! as it is a function name, so is feradios.
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; } (); function dateInArray(queryDate){ return Boolean(feriados.filter(function(date){ return date.isSame(queryDate); }).length); // return feriados.some(date => date.isSame(queryDate)); } console.log(dateInArray(moment('2016-12-25'))); console.log(dateInArray(moment('2016-12-28')));
<script src="http://momentjs.com/downloads/moment.min.js"></script>
I would rather convert moment date object to number (timeSpan) with.valueOf() method and then compare two numbers
function checkFeriado(data) {
var i;
for (i = 0; i < allFeriados.length; i++) {
if (allFeriados[i].valueOf() == data.value()) {
return true;
}
}
return false;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.