Devo controllare se justPrices[i].substr(commapos+2,1).
La stringa è qualcosa del tipo: "blabla, 120"
In questo caso controllerebbe se "0" è un numero. Come si può fare?
Devo controllare se justPrices[i].substr(commapos+2,1).
La stringa è qualcosa del tipo: "blabla, 120"
In questo caso controllerebbe se "0" è un numero. Come si può fare?
Risposte:
È possibile utilizzare operatori di confronto per vedere se è compreso nell'intervallo di caratteri numerici:
var c = justPrices[i].substr(commapos+2,1);
if (c >= '0' && c <= '9') {
// it is a number
} else {
// it isn't
}
puoi usare parseInte poi controllare conisNaN
o se vuoi lavorare direttamente sulla tua stringa puoi usare regexp in questo modo:
function is_numeric(str){
return /^\d+$/.test(str);
}
function is_numeric_char(c) { return /\d/.test(c); }
is_numeric_char("foo1bar") == true). se vuoi controllare un carattere numerico /^\d$/.test(c)sarebbe una soluzione migliore. ma comunque, non era la domanda :)
EDIT: la risposta aggiornata di Blender è la risposta giusta qui se stai solo controllando un singolo carattere (vale a dire !isNaN(parseInt(c, 10))). La mia risposta di seguito è una buona soluzione se vuoi testare intere stringhe.
Ecco l' isNumericimplementazione di jQuery (in puro JavaScript), che funziona con stringhe complete :
function isNumeric(s) {
return !isNaN(s - parseFloat(s));
}
Il commento per questa funzione recita:
// parseFloat NaNs falsi positivi con cast numerico (null | true | false | "")
// ... ma interpreta male le stringhe dei numeri iniziali, in particolare i letterali esadecimali ("0x ...")
// la sottrazione forza gli infiniti a NaN
Penso che possiamo fidarci del fatto che questi ragazzi abbiano dedicato un bel po 'di tempo a questo!
Mi chiedo perché nessuno abbia pubblicato una soluzione come:
var charCodeZero = "0".charCodeAt(0);
var charCodeNine = "9".charCodeAt(0);
function isDigitCode(n) {
return(n >= charCodeZero && n <= charCodeNine);
}
con un'invocazione come:
if (isDigitCode(justPrices[i].charCodeAt(commapos+2))) {
... // digit
} else {
... // not a digit
}
Puoi usare questo:
function isDigit(n) {
return Boolean([true, true, true, true, true, true, true, true, true, true][n]);
}
Qui, l'ho confrontato con il metodo accettato: http://jsperf.com/isdigittest/5 . Non mi aspettavo molto, quindi sono rimasto piuttosto sorpreso quando ho scoperto che il metodo accettato era molto più lento.
La cosa interessante è che mentre il metodo accettato è un input corretto più veloce (es. "5") e più lento per errato (es. "A"), il mio metodo è esattamente opposto (veloce per errato e più lento per corretto).
Tuttavia, nel peggiore dei casi, il mio metodo è 2 volte più veloce della soluzione accettata per un input corretto e oltre 5 volte più veloce per un input errato.
!!([!0, !0, !0, !0, !0, !0, !0, !0, !0, !0][n]);ha un grande potenziale WTF e funziona abbastanza bene (fallisce per 007).
"length"(e altri attributi trovati sugli array) sono cifre: P
Penso che sia molto divertente trovare modi per risolvere questo problema. Di seguito sono riportati alcuni.
(Tutte le funzioni seguenti presumono che l' argomento sia un singolo carattere. Modificare in n[0]per applicarlo)
function isCharDigit(n){
return !!n.trim() && n > -1;
}
function isCharDigit(n){
return !!n.trim() && n*0==0;
}
function isCharDigit(n){
return !!n.trim() && !!Number(n+.1); // "+.1' to make it work with "." and "0" Chars
}
var isCharDigit = (function(){
var a = [1,1,1,1,1,1,1,1,1,1];
return function(n){
return !!a[n] // check if `a` Array has anything in index 'n'. Cast result to boolean
}
})();
function isCharDigit(n){
return !!n.trim() && !isNaN(+n);
}
var str = ' 90ABcd#?:.+', char;
for( char of str )
console.log( char, isCharDigit(char) );
trueper " ".
charCodeAt()confronto - che era quasi 4 volte più veloce - jsperf.com/isdigit3
Funzione semplice
function isCharNumber(c){
return c >= '0' && c <= '9';
}
Suggerisco una semplice regex.
Se stai cercando solo l'ultimo carattere nella stringa:
/^.*?[0-9]$/.test("blabla,120"); // true
/^.*?[0-9]$/.test("blabla,120a"); // false
/^.*?[0-9]$/.test("120"); // true
/^.*?[0-9]$/.test(120); // true
/^.*?[0-9]$/.test(undefined); // false
/^.*?[0-9]$/.test(-1); // true
/^.*?[0-9]$/.test("-1"); // true
/^.*?[0-9]$/.test(false); // false
/^.*?[0-9]$/.test(true); // false
E la regex è ancora più semplice se stai solo controllando un singolo carattere come input:
var char = "0";
/^[0-9]$/.test(char); // true
La soluzione più breve è:
const isCharDigit = n => n < 10;
Puoi applicare anche questi:
const isCharDigit = n => Boolean(++n);
const isCharDigit = n => '/' < n && n < ':';
const isCharDigit = n => !!++n;
se vuoi controllare più di 1 chatacter, potresti usare le varianti successive
Espressione regolare:
const isDigit = n => /\d+/.test(n);
Confronto:
const isDigit = n => +n == n;
Controlla se non è NaN
const isDigit = n => !isNaN(n);
isNumber = function(obj, strict) {
var strict = strict === true ? true : false;
if (strict) {
return !isNaN(obj) && obj instanceof Number ? true : false;
} else {
return !isNaN(obj - parseFloat(obj));
}
}
output senza modalità rigorosa:
var num = 14;
var textnum = '14';
var text = 'yo';
var nan = NaN;
isNumber(num);
isNumber(textnum);
isNumber(text);
isNumber(nan);
true
true
false
false
output con modalità rigorosa:
var num = 14;
var textnum = '14';
var text = 'yo';
var nan = NaN;
isNumber(num, true);
isNumber(textnum, true);
isNumber(text, true);
isNumber(nan);
true
false
false
false
Questo sembra funzionare:
Legame statico:
String.isNumeric = function (value) {
return !isNaN(String(value) * 1);
};
Rilegatura prototipo:
String.prototype.isNumeric = function () {
return !isNaN(this.valueOf() * 1);
};
Controllerà i singoli caratteri, così come intere stringhe per vedere se sono numerici.
function is_numeric(mixed_var) {
return (typeof(mixed_var) === 'number' || typeof(mixed_var) === 'string') &&
mixed_var !== '' && !isNaN(mixed_var);
}
Puoi provare questo (ha funzionato nel mio caso)
Se vuoi verificare se il primo carattere di una stringa è un int:
if (parseInt(YOUR_STRING.slice(0, 1))) {
alert("first char is int")
} else {
alert("first char is not int")
}
Se vuoi verificare se il carattere è un int:
if (parseInt(YOUR_CHAR)) {
alert("first char is int")
} else {
alert("first char is not int")
}
Questa funzione funziona per tutti i casi di test che ho trovato. È anche più veloce di:
function isNumeric (n) {
if (!isNaN(parseFloat(n)) && isFinite(n) && !hasLeading0s(n)) {
return true;
}
var _n = +n;
return _n === Infinity || _n === -Infinity;
}
var isIntegerTest = /^\d+$/;
var isDigitArray = [!0, !0, !0, !0, !0, !0, !0, !0, !0, !0];
function hasLeading0s(s) {
return !(typeof s !== 'string' ||
s.length < 2 ||
s[0] !== '0' ||
!isDigitArray[s[1]] ||
isIntegerTest.test(s));
}
var isWhiteSpaceTest = /\s/;
function fIsNaN(n) {
return !(n <= 0) && !(n > 0);
}
function isNumber(s) {
var t = typeof s;
if (t === 'number') {
return (s <= 0) || (s > 0);
} else if (t === 'string') {
var n = +s;
return !(fIsNaN(n) || hasLeading0s(s) || !(n !== 0 || !(s === '' || isWhiteSpaceTest.test(s))));
} else if (t === 'object') {
return !(!(s instanceof Number) || fIsNaN(+s));
}
return false;
}
function testRunner(IsNumeric) {
var total = 0;
var passed = 0;
var failedTests = [];
function test(value, result) {
total++;
if (IsNumeric(value) === result) {
passed++;
} else {
failedTests.push({
value: value,
expected: result
});
}
}
// true
test(0, true);
test(1, true);
test(-1, true);
test(Infinity, true);
test('Infinity', true);
test(-Infinity, true);
test('-Infinity', true);
test(1.1, true);
test(-0.12e-34, true);
test(8e5, true);
test('1', true);
test('0', true);
test('-1', true);
test('1.1', true);
test('11.112', true);
test('.1', true);
test('.12e34', true);
test('-.12e34', true);
test('.12e-34', true);
test('-.12e-34', true);
test('8e5', true);
test('0x89f', true);
test('00', true);
test('01', true);
test('10', true);
test('0e1', true);
test('0e01', true);
test('.0', true);
test('0.', true);
test('.0e1', true);
test('0.e1', true);
test('0.e00', true);
test('0xf', true);
test('0Xf', true);
test(Date.now(), true);
test(new Number(0), true);
test(new Number(1e3), true);
test(new Number(0.1234), true);
test(new Number(Infinity), true);
test(new Number(-Infinity), true);
// false
test('', false);
test(' ', false);
test(false, false);
test('false', false);
test(true, false);
test('true', false);
test('99,999', false);
test('#abcdef', false);
test('1.2.3', false);
test('blah', false);
test('\t\t', false);
test('\n\r', false);
test('\r', false);
test(NaN, false);
test('NaN', false);
test(null, false);
test('null', false);
test(new Date(), false);
test({}, false);
test([], false);
test(new Int8Array(), false);
test(new Uint8Array(), false);
test(new Uint8ClampedArray(), false);
test(new Int16Array(), false);
test(new Uint16Array(), false);
test(new Int32Array(), false);
test(new Uint32Array(), false);
test(new BigInt64Array(), false);
test(new BigUint64Array(), false);
test(new Float32Array(), false);
test(new Float64Array(), false);
test('.e0', false);
test('.', false);
test('00e1', false);
test('01e1', false);
test('00.0', false);
test('01.05', false);
test('00x0', false);
test(new Number(NaN), false);
test(new Number('abc'), false);
console.log('Passed ' + passed + ' of ' + total + ' tests.');
if (failedTests.length > 0) console.log({
failedTests: failedTests
});
}
testRunner(isNumber)
Per quanto ne so, il modo più semplice è moltiplicare per 1:
var character = ... ; // your character
var isDigit = ! isNaN(character * 1);
La moltiplicazione per uno crea un numero da qualsiasi stringa numerica (poiché hai un solo carattere, sarà sempre un numero intero da 0 a 9) e a NaNper qualsiasi altra stringa.
Simile a una delle risposte sopra, ho usato
var sum = 0; //some value
let num = parseInt(val); //or just Number.parseInt
if(!isNaN(num)) {
sum += num;
}
Questo post sul blog fa luce su questo controllo se una stringa è numerica in Javascript | Dattiloscritto e ES6
Una soluzione semplice sfruttando il controllo dinamico del tipo del linguaggio:
function isNumber (string) {
//it has whitespace
if(string === ' '.repeat(string.length)){
return false
}
return string - 0 === string * 1
}
vedere i casi di test di seguito
Basta usare isFinite
const number = "1";
if (isFinite(number)) {
// do something
}