Risposte:
Stai facendo una domanda sui confronti numerici, quindi le espressioni regolari non hanno davvero nulla a che fare con il problema. Non hai nemmeno bisogno di ifistruzioni "multiple " per farlo:
if (x >= 0.001 && x <= 0.009) {
// something
}
Potresti scrivere una funzione "between ()":
function between(x, min, max) {
return x >= min && x <= max;
}
// ...
if (between(x, 0.001, 0.009)) {
// something
}
Ecco un'opzione con un solo confronto.
// return true if in range, otherwise false
function inRange(x, min, max) {
return ((x-min)*(x-max) <= 0);
}
console.log(inRange(5, 1, 10)); // true
console.log(inRange(-5, 1, 10)); // false
console.log(inRange(20, 1, 10)); // false
Se devi usare una regexp (e davvero, non dovresti!) Funzionerà:
/^0\.00([1-8]\d*|90*)$/
dovrebbe funzionare, ad es
^ niente prima,0.00(nb: backslash escape per il .carattere)$: seguito da nient'altroSe stai già utilizzando lodash, puoi utilizzare la inRange()funzione:
https://lodash.com/docs/4.17.15#inRange
_.inRange(3, 2, 4);
// => true
_.inRange(4, 8);
// => true
_.inRange(4, 2);
// => false
_.inRange(2, 2);
// => false
_.inRange(1.2, 2);
// => true
_.inRange(5.2, 4);
// => false
_.inRange(-3, -2, -6);
// => true
Mi piace la betweenfunzione di Pointy, quindi ne ho scritta una simile che ha funzionato bene per il mio scenario.
/**
* Checks if an integer is within ±x another integer.
* @param {int} op - The integer in question
* @param {int} target - The integer to compare to
* @param {int} range - the range ±
*/
function nearInt(op, target, range) {
return op < target + range && op > target - range;
}
quindi, se volessi vedere se xera entro ± 10 da y:
var x = 100;
var y = 115;
nearInt(x,y,10) = false
Lo sto usando per rilevare una pressione prolungata sul cellulare:
//make sure they haven't moved too much during long press.
if (!nearInt(Last.x,Start.x,5) || !nearInt(Last.y, Start.y,5)) clearTimeout(t);
Se desideri che il tuo codice scelga un intervallo specifico di cifre, assicurati di utilizzare l' &&operatore invece del ||.
if (x >= 4 && x <= 9) {
// do something
} else {
// do something else
}
// be sure not to do this
if (x >= 4 || x <= 9) {
// do something
} else {
// do something else
}
È necessario determinare il limite inferiore e superiore prima di scrivere la condizione
function between(value,first,last) {
let lower = Math.min(first,last) , upper = Math.max(first,last);
return value >= lower && value <= upper ;
}
&&operatore? ...