¿Cómo se comprueba que un número es NaN en JavaScript?
Solo lo he estado probando en la consola JavaScript de Firefox, pero ninguna de las siguientes instrucciones devuelve true:
parseFloat('geoff') == NaN;
parseFloat('geoff') == Number.NaN;
29 answers
Prueba este código:
isNaN(parseFloat("geoff"))
Para verificar si cualquier valor es NaN, en lugar de solo números, vea aquí: ¿Cómo prueba NAN en Javascript?
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:47:30
Acabo de encontrar esta técnica en el libro Eficaz JavaScript {[3] } que es bastante simple:
Dado que NaN es el único valor de JavaScript que se trata como no igual a sí mismo, siempre puede probar si un valor es NaN comprobando su igualdad con él mismo:
var a = NaN;
a !== a; // true
var b = "foo";
b !== b; // false
var c = undefined;
c !== c; // false
var d = {};
d !== d; // false
var e = { valueOf: "foo" };
e !== e; // false
No se dio cuenta de esto hasta que @allsyed comentó, pero esto está en la especificación de ECMA: https://tc39.github.io/ecma262/#sec-isnan-number
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-12 01:32:34
Utilice este código:
isNaN('geoff');
Véase isNaN()
docs on MDN .
alert ( isNaN('abcd')); // alerts true
alert ( isNaN('2.0')); // alerts false
alert ( isNaN(2.0)); // alerts false
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-05 16:08:34
En cuanto a un valor de tipo Número debe ser probado si es un NaN
o no, la función global isNaN
hará el trabajo
isNaN(any-Number);
Para un enfoque genérico que funciona para todos los tipos en JS, podemos usar cualquiera de los siguientes:
Para los usuarios de ECMAScript-5:
#1
if(x !== x) {
console.info('x is NaN.');
}
else {
console.info('x is NOT a NaN.');
}
Para personas que usan ECMAScript-6:
#2
Number.isNaN(x);
Y para propósitos de consistencia en ECMAScript 5 y 6, también podemos usar este polyfill para Numero.isNaN
#3
//Polyfill from MDN
Number.isNaN = Number.isNaN || function(value) {
return typeof value === "number" && isNaN(value);
}
// Or
Number.isNaN = Number.isNaN || function(value) {
return value !== value;
}
Por favor revise Esta respuesta para más detalles.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:44
NaN es un valor especial que no se puede probar así. Una cosa interesante que solo quería compartir es esto
var nanValue = NaN;
if(nanValue !== nanValue) // Returns true!
alert('nanValue is NaN');
Esto devuelve true solo para los valores NaN y es una forma segura de probar. Definitivamente debe estar envuelto en una función o al menos comentado, porque no tiene mucho sentido, obviamente, para probar si la misma variable no es igual entre sí, jeje.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-27 18:39:21
Debe usar la llamada a la función global isNaN(value)
, porque:
- Es compatible con cross-browser
- Véase isNaN para la documentación
Ejemplos:
isNaN('geoff'); // true
isNaN('3'); // false
Espero que esto te ayude.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-05 15:42:50
A partir de ES6, Object.is(..)
es una nueva utilidad que se puede utilizar para probar dos valores de igualdad absoluta:
var a = 3 / 'bar';
Object.is(a, NaN); // true
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-28 03:26:53
Para solucionar el problema donde '1.2geoff'
se analiza, simplemente use el analizador Number()
en su lugar.
Así que en lugar de esto:
parseFloat('1.2geoff'); // => 1.2
isNaN(parseFloat('1.2geoff')); // => false
isNaN(parseFloat('.2geoff')); // => false
isNaN(parseFloat('geoff')); // => true
Haz esto:
Number('1.2geoff'); // => NaN
isNaN(Number('1.2geoff')); // => true
isNaN(Number('.2geoff')); // => true
isNaN(Number('geoff')); // => true
EDITAR: Acabo de notar otro problema de esto sin embargo... los valores falsos (y true como un booleano real) pasados a Number()
devuelven como 0
! En cuyo caso... parseFloat funciona cada vez en su lugar. Así que vuelve a eso:
function definitelyNaN (val) {
return isNaN(val && val !== true ? Number(val) : parseFloat(val));
}
Y eso cubre aparentemente todo. Lo comparé en un 90% más lento que el de lodash _.isNaN
pero luego ese no cubre todas las nanas:
Http://jsperf.com/own-isnan-vs-underscore-lodash-isnan
Solo para ser claros, la mía se encarga de la interpretación literal humana de algo que "No es un Número" y la de lodash se encarga de la interpretación literal de la computadora de verificar si algo es "NaN".
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-24 10:11:39
Mientras que la respuesta de @chiborg ES correcta, hay más que debe notarse:
parseFloat('1.2geoff'); // => 1.2
isNaN(parseFloat('1.2geoff')); // => false
isNaN(parseFloat('.2geoff')); // => false
isNaN(parseFloat('geoff')); // => true
El punto es, si está utilizando este método para la validación de entrada, el resultado será bastante liberal.
Por lo tanto, sí puede usar parseFloat(string)
(o en el caso de números completos parseInt(string, radix)
' y luego envolver eso con isNaN()
, pero tenga en cuenta el gotcha con números entrelazados con caracteres no numéricos adicionales.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-24 23:08:25
Solución simple!
REALMENTE súper simple! Aquí! Tiene este método!
function isReallyNaN(a) { return a !== a; };
Utilice tan simple como:
if (!isReallyNaN(value)) { return doingStuff; }
Ver prueba de rendimiento aquí el uso de este func vs respuesta seleccionada
También: Vea el siguiente 1er ejemplo para un par de implementaciones alternativas.
Ejemplo:
function isReallyNaN(a) { return a !== a; };
var example = {
'NaN': NaN,
'an empty Objet': {},
'a parse to NaN': parseFloat('$5.32'),
'a non-empty Objet': { a: 1, b: 2 },
'an empty Array': [],
'a semi-passed parse': parseInt('5a5'),
'a non-empty Array': [ 'a', 'b', 'c' ],
'Math to NaN': Math.log(-1),
'an undefined object': undefined
}
for (x in example) {
var answer = isReallyNaN(example[x]),
strAnswer = answer.toString();
$("table").append($("<tr />", { "class": strAnswer }).append($("<th />", {
html: x
}), $("<td />", {
html: strAnswer
})))
};
table { border-collapse: collapse; }
th, td { border: 1px solid; padding: 2px 5px; }
.true { color: red; }
.false { color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table></table>
Hay un par de caminos alternativos que tomas para implementaion, si no desea utilizar un método con nombre alternativo, y le gustaría asegurarse de que esté más disponible a nivel mundial. Aviso Estas soluciones implican alterar objetos nativos, y pueden no ser su mejor solución. Siempre tenga cuidado y tenga en cuenta que otras bibliotecas que pueda usar pueden depender de código nativo o alteraciones similares.
Implementación alternativa 1: Reemplazar el método nativo isNaN
.
// Extremely simple. Just simply write the method.
window.isNaN = function(a) { return a !==a; }
Alternate Implementation 2: Append to Number Objeto
*Se sugiere, ya que también es un relleno de polietileno para ECMA 5 a 6
Number['isNaN'] || (Number.isNaN = function(a) { return a !== a });
// Use as simple as
Number.isNaN(NaN)
Solución alternativa prueba si está vacía
Un método de ventana simple Escribí esa prueba si el objeto es Vacío. Es un poco diferente en que no da si item es "exactamente" NaN, pero pensé que podría lanzar esto ya que también puede ser útil cuando se busca vacío elemento.
/** isEmpty(varried)
* Simple method for testing if item is "empty"
**/
;(function() {
function isEmpty(a) { return (!a || 0 >= a) || ("object" == typeof a && /\{\}|\[(null(,)*)*\]/.test(JSON.stringify(a))); };
window.hasOwnProperty("empty")||(window.empty=isEmpty);
})();
Ejemplo:
;(function() {
function isEmpty(a) { return !a || void 0 === a || a !== a || 0 >= a || "object" == typeof a && /\{\}|\[(null(,)*)*\]/.test(JSON.stringify(a)); };
window.hasOwnProperty("empty")||(window.empty=isEmpty);
})();
var example = {
'NaN': NaN,
'an empty Objet': {},
'a parse to NaN': parseFloat('$5.32'),
'a non-empty Objet': { a: 1, b: 2 },
'an empty Array': new Array(),
'an empty Array w/ 9 len': new Array(9),
'a semi-passed parse': parseInt('5a5'),
'a non-empty Array': [ 'a', 'b', 'c' ],
'Math to NaN': Math.log(-1),
'an undefined object': undefined
}
for (x in example) {
var answer = empty(example[x]),
strAnswer = answer.toString();
$("#t1").append(
$("<tr />", { "class": strAnswer }).append(
$("<th />", { html: x }),
$("<td />", { html: strAnswer.toUpperCase() })
)
)
};
function isReallyNaN(a) { return a !== a; };
for(x in example){var answer=isReallyNaN(example[x]),strAnswer=answer.toString();$("#t2").append($("<tr />",{"class":strAnswer}).append($("<th />",{html:x}),$("<td />",{html:strAnswer.toUpperCase()})))};
table { border-collapse: collapse; float: left; }
th, td { border: 1px solid; padding: 2px 5px; }
.true { color: red; }
.false { color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table id="t1"><thead><tr><th colspan="2">isEmpty()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table>
<table id="t2"><thead><tr><th colspan="2">isReallyNaN()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table>
Verificación Extremadamente Profunda Si Está Vacía
Este último va un poco profundo, incluso comprobando si un Objeto está lleno de Objetos en blanco. Estoy seguro de que tiene margen de mejora y posibles hoyos, pero hasta ahora, parece atrapar casi todo.
function isEmpty(a) {
if (!a || 0 >= a) return !0;
if ("object" == typeof a) {
var b = JSON.stringify(a).replace(/"[^"]*":(0|"0*"|false|null|\{\}|\[(null(,)?)*\]),?/g, '').replace(/"[^"]*":\{\},?/g, '');
if ( /^$|\{\}|\[\]/.test(b) ) return !0;
else if (a instanceof Array) {
b = b.replace(/(0|"0*"|false|null|\{\}|\[(null(,)?)*\]),?/g, '');
if ( /^$|\{\}|\[\]/.test(b) ) return !0;
}
}
return false;
}
window.hasOwnProperty("empty")||(window.empty=isEmpty);
var example = {
'NaN': NaN,
'an empty Objet': {},
'a parse to NaN': parseFloat('$5.32'),
'a non-empty Objet': { a: 1, b: 2 },
'an empty Array': new Array(),
'an empty Array w/ 9 len': new Array(9),
'a semi-passed parse': parseInt('5a5'),
'a non-empty Array': [ 'a', 'b', 'c' ],
'Math to NaN': Math.log(-1),
'an undefined object': undefined,
'Object Full of Empty Items': { 1: '', 2: [], 3: {}, 4: false, 5:new Array(3), 6: NaN, 7: null, 8: void 0, 9: 0, 10: '0', 11: { 6: NaN, 7: null, 8: void 0 } },
'Array Full of Empty Items': ["",[],{},false,[null,null,null],null,null,null,0,"0",{"6":null,"7":null}]
}
for (x in example) {
var answer = empty(example[x]),
strAnswer = answer.toString();
$("#t1").append(
$("<tr />", { "class": strAnswer }).append(
$("<th />", { html: x }),
$("<td />", { html: strAnswer.toUpperCase() })
)
)
};
function isReallyNaN(a) { return a !== a; };
for(x in example){var answer=isReallyNaN(example[x]),strAnswer=answer.toString();$("#t2").append($("<tr />",{"class":strAnswer}).append($("<th />",{html:x}),$("<td />",{html:strAnswer.toUpperCase()})))};
table { border-collapse: collapse; float: left; }
th, td { border: 1px solid; padding: 2px 5px; }
.true { color: red; }
.false { color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table id="t1"><thead><tr><th colspan="2">isEmpty()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table>
<table id="t2"><thead><tr><th colspan="2">isReallyNaN()</th></tr></thead><thead><tr><th>Value Type</th><th>Bool Return</th></tr></thead></table>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:44
Si su entorno es compatible con ECMAScript 2015, entonces es posible que desee utilizar Number.isNaN
para asegurarse de que el valor es realmente NaN
.
El problema con isNaN
es, si utiliza que con datos no numéricos hay pocas reglas confusas (según MDN) se aplican. Por ejemplo,
isNaN(NaN); // true
isNaN(undefined); // true
isNaN({}); // true
Por lo tanto, en los entornos compatibles con ECMA Script 2015, es posible que desee usar
Number.isNaN(parseFloat('geoff'))
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-14 15:32:09
Utilizo guiones bajos isNaN
función porque en JavaScript:
isNaN(undefined)
-> true
Por lo menos, ser consciente de que gotcha.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-09 01:46:31
NaN en JavaScript significa "Not A Number", aunque su tipo es en realidad number.
typeof(NaN) // "number"
Para comprobar si una variable es de valor NaN, no podemos simplemente usar la función isNaN(), porque isNaN() tiene el siguiente problema, ver a continuación:
var myVar = "A";
isNaN(myVar) // true, although "A" is not really of value NaN
Lo que realmente sucede aquí es que míVar está implícitamente coaccionado a un número:
var myVar = "A";
isNaN(Number(myVar)) // true. Number(myVar) is NaN here in fact
En realidad tiene sentido, porque "A" en realidad no es un número. Pero lo que realmente queremos comprobar es si myVar es exactamente de valor NaN.
So isNaN () no puede ayudar. Entonces, ¿qué deberíamos hacer en su lugar?
A la luz de que NaN es el único valor de JavaScript que es tratado de manera desigual con respecto a sí mismo, por lo que podemos verificar su igualdad con respecto a sí mismo usando !==
var myVar; // undefined
myVar !== myVar // false
var myVar = "A";
myVar !== myVar // false
var myVar = NaN
myVar !== myVar // true
Así que, para concluir, si es cierto que una variable != = en sí misma, entonces esta variable es exactamente de valor NaN:
function isOfValueNaN(v) {
return v !== v;
}
var myVar = "A";
isNaN(myVar); // true
isOfValueNaN(myVar); // false
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-09 08:40:40
Parece que isNaN() no está soportado en Node.js fuera de la caja.
He trabajado con
var value = 1;
if (parseFloat(stringValue)+"" !== "NaN") value = parseFloat(stringValue);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-05-06 09:05:15
Solo quiero compartir otra alternativa, no es necesariamente mejor que otras aquí, pero creo que vale la pena mirar:
function customIsNaN(x) { return (typeof x == 'number' && x != 0 && !x); }
La lógica detrás de esto es que todos los números excepto 0
y NaN
se lanzan a true
.
He hecho una prueba rápida, y funciona tan bien como Number.isNaN
y como comprobación contra sí mismo para falso. Los tres funcionan mejor que isNan
Los resultados
customIsNaN(NaN); // true
customIsNaN(0/0); // true
customIsNaN(+new Date('?')); // true
customIsNaN(0); // false
customIsNaN(false); // false
customIsNaN(null); // false
customIsNaN(undefined); // false
customIsNaN({}); // false
customIsNaN(''); // false
Puede ser útil si desea evitar la función isNaN
rota.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-03-20 14:13:11
NaN === NaN; // false
Number.NaN === NaN; // false
isNaN(NaN); // true
isNaN(Number.NaN); // true
El operador de igualdad (== y ===) no se puede usar para probar un valor contra NaN.
Mira La documentación de Mozilla La propiedad NAN global es un valor que representa Not-A-Numbe
La mejor manera es usar 'isNaN()' que es la función buit-in para comprobar NaN. Todos los navegadores admiten el camino..
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-08 22:18:25
La forma exacta de comprobar es:
//takes care of boolen, undefined and empty
isNaN(x) || typeof(x) ==='boolean' || typeof(x) !=='undefined' || x!=='' ? 'is really a nan' : 'is a number'
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-30 04:36:19
function isNotANumber(n) {
if (typeof n !== 'number') {
return true;
}
return n !== n;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-30 11:59:12
Tal vez también esto:
function isNaNCustom(value){
return value.toString() === 'NaN' &&
typeof value !== 'string' &&
typeof value === 'number'
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-01 13:30:50
De acuerdo con IEEE 754, todas las relaciones que involucran a NaN se evalúan como falsas, excepto !=. Así, por ejemplo, (A >= B) = false y (A
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-28 20:09:04
Escribí esta respuesta a otra pregunta en StackOverflow donde otro comprueba cuando NaN == null
pero luego fue marcado como duplicado, así que no quiero perder mi trabajo.
Mira Mozilla Developer Network acerca de NaN
.
Respuesta corta
Simplemente use distance || 0
cuando quiera asegurarse de que el valor es un número adecuado o isNaN()
para verificarlo.
Respuesta larga
El NaN (Not-a-Number) es un extraño Objeto Global en javascript frecuentemente regresaba cuando alguna operación matemática fallaba.
Quería comprobar si NaN == null
que resulta false
. Hovewer even NaN == NaN
resultados con false
.
Una forma sencilla de averiguar si la variable es NaN
es una función global isNaN()
.
Otro es x !== x
que solo es cierto cuando x es NaN. (gracias por recordar a @ raphael-schweikert)
Pero, ¿por qué funcionó la respuesta corta?
Averigüémoslo.
Cuando llamas a NaN == false
el resultado es false
, lo mismo con NaN == true
.
En algún lugar de las especificaciones JavaScript tiene un registro con valores siempre falsos, que incluye:
-
NaN
- Not-a-Number -
""
- cadena vacía -
false
- un falso booleano -
null
- objeto nulo -
undefined
- variables indefinidas -
0
- numérico 0, incluyendo +0 y -0
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:44
Otra solución se menciona en La página de parseFloat de MDN
Proporciona una función de filtro para hacer un análisis estricto
var filterFloat = function (value) {
if(/^(\-|\+)?([0-9]+(\.[0-9]+)?|Infinity)$/
.test(value))
return Number(value);
return NaN;
}
console.log(filterFloat('421')); // 421
console.log(filterFloat('-421')); // -421
console.log(filterFloat('+421')); // 421
console.log(filterFloat('Infinity')); // Infinity
console.log(filterFloat('1.61803398875')); // 1.61803398875
console.log(filterFloat('421e+0')); // NaN
console.log(filterFloat('421hop')); // NaN
console.log(filterFloat('hop1.61803398875')); // NaN
Y luego puedes usar isNaN
para comprobar si es NaN
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-04 17:22:36
He creado esta pequeña función que funciona como un encanto. En lugar de comprobar para NaN que parece ser contra intuitivo, usted busca un número. Estoy bastante seguro de que no soy el primero en hacerlo de esta manera, pero pensé en compartir.
function isNum(val){
var absVal = Math.abs(val);
var retval = false;
if((absVal-absVal) == 0){
retval = true
}
return retval;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-05 20:14:33
Encontré otra manera, solo por diversión.
function IsActuallyNaN(obj) {
return [obj].includes(NaN);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-19 04:43:00
La respuesta de Marksyzm funciona bien, pero no devuelve false para Infinity
ya que Infinity no es técnicamente un número.
Se me ocurrió una función isNumber
que comprobará si es un número.
function isNumber(i) {
return !isNaN(i && i !== true ? Number(i) : parseFloat(i)) && [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY].indexOf(i) === -1;
}
console.log(isNumber(Infinity));
console.log(isNumber("asdf"));
console.log(isNumber(1.4));
console.log(isNumber(NaN));
console.log(isNumber(Number.MAX_VALUE));
console.log(isNumber("1.68"));
ACTUALIZAR: me di cuenta de que este código falla para algunos parámetros, así que lo hice mejor.
function isNumber(i) {//function for checking if parameter is number
if(!arguments.length) {
throw new SyntaxError("not enough arguments.");
} else if(arguments.length > 1) {
throw new SyntaxError("too many arguments.");
} else if([Number.NEGATIVE_INFINITY, Number.POSITIVE_INFINITY].indexOf(i) !== -1) {
throw new RangeError("number cannot be \xB1infinity.");
} else if(typeof i === "object" && !(i instanceof RegExp) && !(i instanceof Number) && !(i === null)) {
throw new TypeError("parameter cannot be object/array.");
} else if(i instanceof RegExp) {
throw new TypeError("parameter cannot be RegExp.");
} else if(i == null || i === undefined) {
throw new ReferenceError("parameter is null or undefined.");
} else {
return !isNaN(i && i !== true ? Number(i) : parseFloat(i)) && (i === i);
}
}
console.log(isNumber(Infinity));
console.log(isNumber(this));
console.log(isNumber(/./ig));
console.log(isNumber(null));
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-10 23:24:16
alert("1234567890.".indexOf(String.fromCharCode(mycharacter))>-1);
Esto no es elegante. pero después de intentar isNaN() llegué a esta solución que es otra alternativa. En este ejemplo también permití '. porque estoy enmascarando a Float. También puede revertir esto para asegurarse de que no se utilicen números.
("1234567890".indexOf(String.fromCharCode(mycharacter))==-1)
Esta es una evaluación de un solo carácter, pero también puede hacer un bucle a través de una cadena para verificar si hay números.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-16 19:38:10
Es (NaN >= 0) ?...... " No lo sé ".
function IsNotNumber( i ){
if( i >= 0 ){ return false; }
if( i <= 0 ){ return false; }
return true;
}
Las condiciones solo se ejecutan si TRUE.
No en FALSO .
No en " No lo sé".
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-18 21:57:22
Así que veo varias respuestas a esto,
Pero yo solo uso:
function isNaN(x){
return x == x && typeof x == 'number';
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-18 22:57:38
Simplemente convierta el resultado en Cadena y compare con 'NaN'.
var val = Number("test");
if(String(val) === 'NaN') {
console.log("true");
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-23 11:42:36