Sto tentando di capire i tipi nel mondo JavaScript. La mia pagina utilizza moment.js. Ho una funzione che a volte restituisce un moment()
e altre volte, restituisce un string
(è il codice legacy impazzito).JavaScript instanceof e moment.js
Il mio codice tipo di assomiglia a questo:
var now = getDate();
if (now instanceof moment) {
console.log('we have a moment.');
} else {
console.log('we have a string.');
}
function getDate() {
var result = null;
// Sometimes result will be a moment(), other times, result will be a string.
result = moment();
return result;
}
Quando eseguo il codice di cui sopra, non ho mai ottenere we have a moment.
. Anche se eseguo manualmente il set result = moment();
. Perché? Sto fraintendendo instanceof
o moment
?
provare a stampare "tipo di momento()" per assicurarsi che vi aspettate il giusto valore. – michaelAdam
prova a usare typeof e debug: console.log (typeof now); – FrankBr
dovrebbe usare 'typeof now ===" stringa "' – Hacketo