Domanda

Ciao in php posso farlo:

$value = 0;
$test = $value === 0 ? 'it is zero!' : 'It is not zero.';
echo $test;

Come si può fare in JavaScript in 1 riga come in PHP senza usare il classico if - else if dichiarazione?

È stato utile?

Soluzione

Funziona ancora in javascript

value = 0;
var test = (value === 0 ? 'it is zero!' : 'It is not zero.');
console.log(test);

Produzione

it is zero!

Altri suggerimenti

Questo dovrebbe funzionare:

var value = 0;
var test = (value === 0) ? 'It is zero' : 'It is not zero!';
console.log(test);

A proposito, si chiama operatore ternario. Molte lingue le supportano.

Quasi esattamente lo stesso.

var value = 0;
var test = (value === 0) ? 'it is zero!' : 'it is not zero';
console.log(test);

Produzione:

"it is zero!"
(value == 0)?alert('it is zero!'):alert('It is not zero.');

Non esiste una differenza così importante tranne che il tuo $ diventa var.

documentazione

Preferisco sempre Ternary per inline. Lo trovo personalmente più leggibile.

var test =(value===0)?'it is zero!':'It is not zero.';
console.log("test check==="+test)

Demo: http://jsfiddle.net/jayeshjain24/eflyf/

Posso farti 1 meglio in js:

var value = 0;
console.log(value === 0 ? 'It is zero!' : 'it is not zero');

O anche più corto:

console.log('it is ' + ((value = 0) === 0 ? '':'not ') + 'zero!');

Bang, una riga per le tue 3 linee PHP. Nota che questo volere risultato in un errore lanciato (in modalità rigorosa) o in una variabile globale implicita che viene creata, se value non esiste.
Tuttavia, se la variabile value Esiste già, tutto funziona perfettamente e il comportamento è come ti aspetteresti che sia:

var value = 0;
console.log('it is ' + ((value = value || 0) === 0 ? '':'not ') + 'zero!');
//logs it is zero
value = 123;
console.log('it is ' + ((value = value || 0) === 0 ? '':'not ') + 'zero!');
//logs it is not zero

L'ho provato usando un IIfe:

(function(value)
{//logs it is zero
    console.log('it is ' + ((value = value || 0) === 0 ? '':'not ') + 'zero!');
}());
    (function(value)
{//logs it is not zero
    console.log('it is ' + ((value = value || 0) === 0 ? '':'not ') + 'zero!');
}(123));
(function(value)
{//logs it is zero
    console.log('it is ' + ((value = value || 0) === 0 ? '':'not ') + 'zero!');
}(0));

Per evitare il codice da Loggin it is zero Quando il valore non è definito o falsy:

(function(value)
{//coerce to numbner
    console.log('it is ' + (value === 0 || value === '0' ? '':'not ') + 'zero!');
}());

Questo registrerà solo it is zero Se value è neanche '0' o 0. Non per valori come false, undefined, null...

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top