2011-01-04 11 views
42

Come posso verificare se una variabile è vuota in Javascript? Scusa per la domanda stupida, ma sono un novizio in Javascript!Il controllo di qualcosa è Vuoto in Javascript?

if(response.photo) is empty { 
    do something 
else { 
    do something else 
} 

response.photo era di JSON, e potrebbe essere a volte vuote, le celle di dati vuote! Voglio verificare se è vuoto.

+1

Cosa significa "vuoto" qui? Se non sei sicuro, mostraci un codice. – thejh

+0

Vuoi dire se non è ancora inizializzato? –

+0

Vuoi dire se valuta 'falso'? –

risposta

62

Se stai testando per una stringa vuota:

if(myVar === ''){ // do stuff }; 

Se stai verificando una variabile dichiarata, ma non definita:

if(myVar === null){ // do stuff }; 

Se stai controllando per una variabile che non può essere definito:

if(myVar === undefined){ // do stuff }; 

Se si sta verificando tanto vale a dire, sia variabile è null o undefined:

if(myVar == null){ // do stuff }; 
+0

se una cella dati vuota dal database, deos che significa indefinito !!! –

+2

Non utilizzare la costante "non definita", poiché non è affatto una costante. Usa 'typeof myVar === 'undefined'' invece. – Guffa

+2

No. Se una variabile è stata dichiarata ma non definita, non è nulla ... non è definita. Se controlli una variabile che non è stata dichiarata, otterrai un errore di runtime. Inoltre, 'var undefined = 1;' interromperà il terzo esempio. Usa sempre 'typeof' e controlla' 'undefined ''. – gilly3

0

Verificare la presenza di indefinito:

if (typeof response.photo == "undefined") 
{ 
    // do something 
} 

Ciò farebbe l'equivelant del vb di IsEmpty. Se myvar contiene qualsiasi valore, anche null, stringa vuota o 0, non è "vuoto".

Per verificare se esiste una variabile o una proprietà, ad esempio è stata dichiarata, sebbene possa non essere stata definita, è possibile utilizzare l'operatore in.

if ("photo" in response) 
{ 
    // do something 
} 
0

Dipende da cosa si intende per "vuoto". Lo schema più comune è verificare se la variabile è undefined. Molte persone anche fare un controllo null, ad esempio:
if (myVariable === undefined || myVariable === null)...

o, in una forma più breve:
if (myVariable || myVariable === null)...

+0

Non utilizzare la costante "non definita", poiché non è affatto una costante. Usa 'typeof myVar === 'undefined'' invece. – Guffa

+0

Queste due forme non sono affatto le stesse. – kapa

+0

Vero, c'è un tipo non definito, ma per citare lo standard: Un riferimento è un binding di nome risolto. Un riferimento è costituito da tre componenti, il valore di base, il nome di riferimento e il flag di riferimento rigoroso con valori booleani. Il valore base è indefinito, un oggetto, un valore booleano, una stringa, un numero o un record di ambiente (10.2.1). Un valore base di indefinito indica che il riferimento non può essere risolto in un binding. –

0
if (myVar == undefined) 

funzionerà per vedere se la var è dichiarata ma non initalizzata.

+1

Questo è pericoloso poiché 'undefined' può essere ridefinito nel codice (vale a dire' undefined = true' è valido). – Tomalak

+0

Non utilizzare la costante "non definita", poiché non è affatto una costante. Usa 'typeof myVar === 'undefined'' invece. – Guffa

0

Se stai cercando l'equivalente della funzione di PHP empty, check this out:

function empty(mixed_var) { 
    // example 1: empty(null); 
    // returns 1: true 
    // example 2: empty(undefined); 
    // returns 2: true 
    // example 3: empty([]); 
    // returns 3: true 
    // example 4: empty({}); 
    // returns 4: true 
    // example 5: empty({'aFunc' : function() { alert('humpty'); } }); 
    // returns 5: false 

    var undef, key, i, len; 
    var emptyValues = [undef, null, false, 0, '', '0']; 

    for (i = 0, len = emptyValues.length; i < len; i++) { 
    if (mixed_var === emptyValues[i]) { 
     return true; 
    } 
    } 

    if (typeof mixed_var === 'object') { 
    for (key in mixed_var) { 
     // TODO: should we check for own properties only? 
     //if (mixed_var.hasOwnProperty(key)) { 
     return false; 
     //} 
    } 
    return true; 
    } 

    return false; 
} 

http://phpjs.org/functions/empty:392

41

Questa è una domanda più grande di quanto si pensi. Le variabili possono svuotarsi in molti modi. Dipende da cosa devi sapere.

// quick and dirty will be true for '', null, undefined, 0, NaN and false. 
if (!x) 

// test for null OR undefined 
if (x == null) 

// test for undefined OR null 
if (x == undefined) 

// test for undefined 
if (x === undefined) 
// or safer test for undefined since the variable undefined can be set causing tests against it to fail. 
if (typeof x == 'undefined') 

// test for empty string 
if (x === '') 

// if you know its an array 
if (x.length == 0) 
// or 
if (!x.length) 

// BONUS test for empty object 
var empty = true, fld; 
for (fld in x) { 
    empty = false; 
    break; 
} 
+3

+1. Dovrebbe essere 'typeof x ===" undefined "', comunque. – Tomalak

+0

@Tomalak Oops, grazie. Penso che il triplo è facoltativo però. Il tipo restituirà una stringa, nulla verrà forzato. – Hemlock

+0

È vero. Ad ogni modo il controllo dell'identità non fa male, immagino. :-) – Tomalak

8

Questo dovrebbe coprire tutti i casi:

function empty(val) { 

    // test results 
    //--------------- 
    // []  true, empty array 
    // {}  true, empty object 
    // null  true 
    // undefined true 
    // ""  true, empty string 
    // ''  true, empty string 
    // 0   false, number 
    // true  false, boolean 
    // false  false, boolean 
    // Date  false 
    // function false 

     if (val === undefined) 
     return true; 

    if (typeof (val) == 'function' || typeof (val) == 'number' || typeof (val) == 'boolean' || Object.prototype.toString.call(val) === '[object Date]') 
     return false; 

    if (val == null || val.length === 0)  // null or 0 length array 
     return true; 

    if (typeof (val) == "object") { 
     // empty object 

     var r = true; 

     for (var f in val) 
      r = false; 

     return r; 
    } 

    return false; 
} 
3

Vedi http://underscorejs.org/#isEmpty

isEmpty_.isEmpty (oggetto) Restituisce vero se un oggetto enumerabile non contiene i valori (non enumerabili proprie proprietà). Per stringhe e oggetti tipo array _.isEmpty controlla se la proprietà length è 0.

2

Vedo potenziali carenze in molte soluzioni postate in precedenza, quindi ho deciso di compilarlo.
Nota: utilizza Array.prototype.some, controllare l'assistenza del browser.

soluzione sotto ritiene variabile vuota se una delle seguenti condizioni:

  1. JS pensa che variabile è uguale a false, che copre già molte cose come 0, "", [], e anche [""] e [0]
  2. valore è null o è tipo è 'undefined'
  3. uno scopo vuoto
  4. Si tratta di un oggetto/array costituito da solo di valori che sono vuoti (ad es. suddiviso in primitive ogni parte di esso equivale a false). Controlla il drill ricorsivamente nella struttura Object/Array. E.g.

    isEmpty({"": 0}) // true 
    isEmpty({"": 1}) // false 
    isEmpty([{}, {}]) // true 
    isEmpty(["", 0, {0: false}]) //true 
    

Codice funzione:

/** 
* Checks if value is empty. Deep-checks arrays and objects 
* Note: isEmpty([]) == true, isEmpty({}) == true, isEmpty([{0:false},"",0]) == true, isEmpty({0:1}) == false 
* @param value 
* @returns {boolean} 
*/ 
function isEmpty(value){ 
    var isEmptyObject = function(a) { 
    if (typeof a.length === 'undefined') { // it's an Object, not an Array 
     var hasNonempty = Object.keys(a).some(function nonEmpty(element){ 
     return !isEmpty(a[element]); 
     }); 
     return hasNonempty ? false : isEmptyObject(Object.keys(a)); 
    } 

    return !a.some(function nonEmpty(element) { // check if array is really not empty as JS thinks 
     return !isEmpty(element); // at least one element should be non-empty 
    }); 
    }; 
    return (
    value == false 
    || typeof value === 'undefined' 
    || value == null 
    || (typeof value === 'object' && isEmptyObject(value)) 
); 
} 
+0

Bello. Puoi indicare le differenze e il modo in cui soddisfa le carenze che hai identificato. –

+1

Avrei bisogno di scorrere tutte le decisioni qui. Ok. Rispetto alle funzioni @victorkohl e @kapa, la mia può andare più in profondità del primo livello e segnalare oggetti complessi che sembrano non vuoti, ma in realtà consistono solo di valori vuoti. Esempio: '[{}, 0," "]'. Tutte le altre soluzioni qui sono solo due righe che non vanno lontano e una funzione di sottolineatura che funziona per gli oggetti e richiede la lib. –

0

quello che mi manca se array vuoto ... oggetto senza chiave ... falsità const isEmpty = O => Array.isArray (o) & &! O.join (''). Lunghezza || typeof o === 'object' & &! Object.keys (o) .length || ! (+ Valore);

0

inserisci la variabile all'interno della condizione if, se la variabile ha un valore restituirà true else false.

if (response.photo){ // if you are checking for string use this if(response.photo == "") condition 
alert("Has Value"); 
} 
else 
{ 
alert("No Value"); 
}; 
+0

Questo presuppone che 'vuoto' significa null ... ma non è chiaro dalla domanda di Asker che questo è ciò che intendevano. Probabilmente è meglio chiarirlo prima, prima di offrire una risposta, o almeno affermarlo come una supposizione nella tua risposta. – Mir

Problemi correlati