Jak Mogę określić, czy zmienna jest 'undefined' lub 'null'?

Jak określić czy zmienna jest undefined Czy null?

Mój kod jest następujący:

var EmpName = $("div#esd-names div#name").attr('class');
if(EmpName == 'undefined'){
  // DO SOMETHING
};
<div id="esd-names">
  <div id="name"></div>
</div>

Ale jeśli to zrobię, interpreter JavaScript zatrzyma wykonanie.

Author: Peter Mortensen, 2010-04-15

30 answers

Możesz użyć właściwości abstrakcyjnego operatora równości aby to zrobić:

if (variable == null){
    // your code here.
}

Ponieważ null == undefined jest prawdą, powyższy kod wychwytuje zarówno null, jak i undefined.

 3033
Author: Sarfraz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-20 20:11:03

Standardowy sposób na złapanie null i undefined jednocześnie jest następujący:

if (variable == null) {
     // do something 
}

-- co jest w 100% równoważne bardziej wyraźnemu, ale mniej zwięzłemu:

if (variable === undefined || variable === null) {
     // do something 
}

Pisząc profesjonalne JS, przyjmuje się za pewnik, że równość typu i zachowanie == vs === zrozumiano. Dlatego używamy == i porównujemy tylko do null.


Edytuj ponownie

Komentarze sugerujące użycie typeof są po prostu Źle. tak, moje rozwiązanie powyżej spowoduje ReferenceError, jeśli zmienna nie istnieje. To dobra rzecz. Ten ReferenceError jest pożądany: pomoże Ci znaleźć błędy i naprawić je przed wysłaniem kodu, tak jak błędy kompilatora w innych językach. Użycie try/catch jeśli pracujesz z danymi wejściowymi, nie masz nad nimi kontroli.

Nie powinieneś mieć żadnych odniesień do nierejestrowanych zmiennych w kodzie.

 1159
Author: temporary_user_name,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-12-20 03:24:53

Łącząc powyższe odpowiedzi, wydaje się, że najbardziej kompletną odpowiedzią będzie:

if( typeof variable === 'undefined' || variable === null ){
    // Do stuff
}

To powinno działać dla każdej zmiennej, która jest albo niezgłoszona, albo zadeklarowana i jawnie ustawiona na null lub undefined. Wyrażenie logiczne powinno mieć wartość false dla każdej zadeklarowanej zmiennej, która ma rzeczywistą wartość inną niż null.

 246
Author: jkindwall,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-09 10:47:36
if (variable == null) {
    // Do stuff, will only match null or undefined, this won't match false
}
 189
Author: knocte,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-26 14:18:58
if (typeof EmpName != 'undefined' && EmpName) {

Będzie oceniać na true, jeśli wartość nie jest:

  • Null

  • Undefined

  • NaN

  • Pusty łańcuch ("")

  • 0

  • Fałsz

 97
Author: Thamaraiselvam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-14 07:33:20

Funkcja JQuery attr() zwraca pusty łańcuch lub rzeczywistą wartość (i nigdy null lub undefined). Zwraca undefined tylko wtedy, gdy selektor nie zwrócił żadnego elementu.

Więc możesz chcieć przetestować na pustym łańcuchu. Alternatywnie, ponieważ puste ciągi, null i undefined są false-y, możesz po prostu zrobić to:

if (!EmpName) { //do something }
 29
Author: Chetan S,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-04-15 18:20:06

Prawdopodobnie najkrótszą drogą do tego jest:

if(EmpName == null) { /* DO SOMETHING */ };

Oto dowód:

function check(EmpName) {
  if(EmpName == null) { return true; };
  return false;
}

var log = (t,a) => console.log(`${t} -> ${check(a)}`);

log('null', null);
log('undefined', undefined);
log('NaN', NaN);
log('""', "");
log('{}', {});
log('[]', []);
log('[1]', [1]);
log('[0]', [0]);
log('[[]]', [[]]);
log('true', true);
log('false', false);
log('"true"', "true");
log('"false"', "false");
log('Infinity', Infinity);
log('-Infinity', -Infinity);
log('1', 1);
log('0', 0);
log('-1', -1);
log('"1"', "1");
log('"0"', "0");
log('"-1"', "-1");

// "void 0" case
console.log('---\n"true" is:', true);
console.log('"void 0" is:', void 0);
log(void 0,void 0); // "void 0" is "undefined" 

A oto więcej szczegółów na temat == (Źródło tutaj )

Tutaj wpisz opis obrazka

BONUS : powód, dla którego === jest bardziej jasny niż == (Spójrz na odpowiedź agc)

Tutaj wpisz opis obrazka

 26
Author: Kamil Kiełczewski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-05-11 08:21:26

Przyszedłem napisać własną funkcję do tego. JavaScript jest dziwny.

Można go używać dosłownie na wszystkim. (Zauważ, że to również sprawdza, czy zmienna zawiera jakiekolwiek użyteczne wartości . Ale ponieważ ta informacja jest zwykle również potrzebna, myślę, że warto zamieścić). Proszę rozważyć pozostawienie notatki.
function empty(v) {
    let type = typeof v;
    if (type === 'undefined') {
        return true;
    }
    if (type === 'boolean') {
        return !v;
    }
    if (v === null) {
        return true;
    }
    if (v === undefined) {
        return true;
    }
    if (v instanceof Array) {
        if (v.length < 1) {
            return true;
        }
    } else if (type === 'string') {
        if (v.length < 1) {
            return true;
        }
        if (v === '0') {
            return true;
        }
    } else if (type === 'object') {
        if (Object.keys(v).length < 1) {
            return true;
        }
    } else if (type === 'number') {
        if (v === 0) {
            return true;
        }
    }
    return false;
}

Kompatybilny z maszynopisem.


Ta funkcja powinna robić dokładnie to samo jak PHP empty() function (zobacz RETURN VALUES)

Rozważa undefined, null, false, 0, 0.0, "0" {}, [] jako puste.

"0.0", NaN, " ", true są uważane za niepuste.

 21
Author: phil294,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-03-08 23:19:22

Najkrótszy i najłatwiejszy:

if(!EmpName ){
 // DO SOMETHING
}

To oceni true, jeśli EmpName to:

  • null
  • undefined
  • NaN
  • empty
  • string ( "" )
  • 0
  • false
 19
Author: userPlus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-08-15 11:58:05

Jeśli zmienna, którą chcesz sprawdzić, jest globalna, wykonaj

if (window.yourVarName) {
    // Your code here
}

Ten sposób sprawdzenia nie spowoduje błędu, nawet jeśli zmienna yourVarName nie istnieje.

Przykład: Chcę wiedzieć, czy moja przeglądarka obsługuje History API

if (window.history) {
    history.back();
}

Jak to działa:

window jest obiektem, który posiada wszystkie zmienne globalne jako swoje właściwości, a w JavaScript jest legalne, aby spróbować uzyskać dostęp do nieistniejącej właściwości obiektu. Jeśli history nie istnieje, to window.history zwraca undefined. undefined jest false, więc kod w bloku if(undefined){} nie będzie działać.

 13
Author: DenisS,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-05 20:37:58

W JavaScript , zgodnie z moją wiedzą, możemy sprawdzić undefined, null lub empty zmienna jak poniżej.

if (variable === undefined){
}

if (variable === null){
}

if (variable === ''){
}

Sprawdź wszystkie warunki:

if(variable === undefined || variable === null || variable === ''){
}
 10
Author: Hardik Desai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-07-01 07:38:17

Ponieważ używasz jQuery , możesz określić, czy zmienna jest niezdefiniowana, czy jej wartość jest null za pomocą pojedynczej funkcji.

var s; // undefined
jQuery.isEmptyObject(s); // will return true;

s = null; // defined as null
jQuery.isEmptyObject(s); // will return true;

// usage
if(jQuery.isEmptyObject(s)){
    alert('Either variable: s is undefined or its value is null');
}else{
     alert('variable: s has value ' + s);
}

s = 'something'; // defined with some value
jQuery.isEmptyObject(s); // will return false;
 9
Author: Angelin Nadar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-06 00:14:01

Właśnie miałem taki problem, czyli sprawdzanie czy obiekt jest null.
Po prostu używam tego:

if (object) {
    // Your code
}

Na przykład:

if (document.getElementById("enterJob")) {
    document.getElementById("enterJob").className += ' current';
}
 9
Author: Welshboy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-05-19 03:34:22

Możesz po prostu użyć poniższego kodu (wiem, że są na to krótsze sposoby, ale może to ułatwić obserwację wizualną, przynajmniej dla innych patrzących na kod).

if (x === null || x === undefined) {
 // Add your response code here, etc.
}
 7
Author: agc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-05-11 08:22:49

JQuery check element not null:

var dvElement = $('#dvElement');

if (dvElement.length  > 0) {
    // Do something
}
else{
    // Else do something else
}
 6
Author: Kapil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-03-08 23:17:31

Najprostszym sposobem sprawdzenia jest:

if(!variable) {
  // If the variable is null or undefined then execution of code will enter here.
}
 4
Author: M. Arnold,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-05-28 06:57:59

Z poniższym rozwiązaniem:

const getType = (val) => typeof val === 'undefined' || !val ? null : typeof val;
const isDeepEqual = (a, b) => getType(a) === getType(b);

console.log(isDeepEqual(1, 1)); // true
console.log(isDeepEqual(null, null)); // true
console.log(isDeepEqual([], [])); // true
console.log(isDeepEqual(1, "1")); // false
etc...

Jestem w stanie sprawdzić:

  • null
  • undefined
  • NaN
  • pusty
  • string ( "" )
  • 0
  • false
 3
Author: Tony Tai Nguyen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-12 10:29:54

Aby sprawdzić czy zmienna jest NULL lub undefined używam poniższego kodu.

    if(typeof sVal === 'undefined' || sVal === null || sVal === ''){
      console.log('variable is undefined or null');
    }
 2
Author: DanKodi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-09-19 23:58:35

Uruchamiam ten test w konsoli Chrome. Używając (void 0) Możesz sprawdzić undefined:

var c;
undefined
if (c === void 0) alert();
// output =  undefined
var c = 1;
// output =  undefined
if (c === void 0) alert();
// output =   undefined
// check c value  c
// output =  1
if (c === void 0) alert();
// output =  undefined
c = undefined;
// output =  undefined
if (c === void 0) alert();
// output =   undefined
 2
Author: suhail,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-03-08 23:21:25

Spójrzmy na to,

  1.  

    let apple; // Only declare the variable as apple
    alert(apple); // undefined
    

    W powyższym przykładzie zmienna jest zadeklarowana tylko jako apple. W tym przypadku wywołanie metody alert wyświetli undefined.

  2.  

       let apple = null; /* Declare the variable as apple and initialized but the value is null */
       alert(apple); // null
    

W drugim wyświetla null, ponieważ zmienna o wartości {[3] } jest null.

Możesz więc sprawdzić, czy wartość jest niezdefiniowana czy null.

if(apple !== undefined || apple !== null) {
    // Can use variable without any error
}
 2
Author: Anjana Kumari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-03-08 23:34:17

Sprawdzanie foo == null powinno załatwić sprawę i rozwiązać "undefined OR null" w najkrótszy sposób. (Nie biorąc pod uwagę przypadku "foo nie jest zadeklarowane".) Ale ludzie, którzy są przyzwyczajeni do 3 równych (jako najlepsza praktyka) może nie zaakceptować. Wystarczy spojrzeć na eqeqeqlub triple-equals zasady w eslint i tslint...

Podejście jawne, kiedy sprawdzamy, czy zmienna jest undefined lub null oddzielnie, powinno być zastosowane w tym przypadku, a mój wkład w temat (27 nie-negatywne odpowiedzi na razie!) jest użycie void 0 jako krótkiego i bezpiecznego sposobu na sprawdzenie undefined.

Używanie foo === undefined nie jest bezpieczne, ponieważ undefined nie jest słowem zastrzeżonym i może być cieniowane (MDN ). Użycie sprawdzania typeof === 'undefined' jest bezpieczne, ale jeśli nie będziemy się przejmować przypadkiem foo-is-undeclared, można zastosować następujące podejście:

if (foo === void 0 || foo === null) { ... }
 2
Author: dhilt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-03-16 23:27:50
(null == undefined)  // true

(null === undefined) // false

Ponieważ = = = sprawdza zarówno typ, jak i wartość. Typ obu są różne, ale wartość jest taka sama.

 1
Author: Franklin Pious,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-27 11:19:18

Jeśli utworzysz funkcję, aby ją sprawdzić:

export function isEmpty (v) {
 if (typeof v === "undefined") {
   return true;
 }
 if (v === null) {
   return true;
 }
 if (typeof v === "object" && Object.keys(v).length === 0) {
   return true;
 }

 if (Array.isArray(v) && v.length === 0) {
   return true;
 }

 if (typeof v === "string" && v.trim().length === 0) {
   return true;
 }

return false;
}
 1
Author: Ernesto,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-05-11 06:09:12

Najlepszy sposób:

if(typeof variable==='undefined' || variable===null) {

/* do your stuff */
}
 0
Author: Nishanth Matha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-25 11:55:10
var i;

if (i === null || typeof i === 'undefined') {
    console.log(i, 'i is undefined or null')
}
else {
    console.log(i, 'i has some value')
}
 0
Author: KARTHIKEYAN.A,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-03-08 23:22:20

Wiem, że spóźniłem się 10 lat. Ale zostawię tu moją odpowiedź na wypadek, gdyby ktoś potrzebował krótkiej metody.

Instalacja Lodash w Twoim projekcie może być przydatna ze względu na funkcje pomocnicze, które mogą się przydać w takich sytuacjach.

Używając modułów ES6, import będzie wyglądał następująco:

import isNull from 'lodash/isNull';

import isUndefined from 'lodash/isUndefined';

import isNil from 'lodash/isNil';

Byłoby lepiej, gdyby tylko używane funkcje były importowane.

Lodash ' s isNull sprawdza, czy wartość jest null.

const value = null;
 
 if(isNull(value)) {
    // do something if null
 }

Lodash ' s isUndefined sprawdza, czy wartość jest niezdefiniowana.

const value = undefined;

if(isUndefined(value)) {
   // do something if undefined.
}

IsNil sprawdza, czy wartość jest null lub undefined. Wolę tę metodę niż dwie pozostałe, ponieważ sprawdza zarówno undefined, jak i null.

 0
Author: Dante_97,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-18 16:35:06

Wywołanie typeof null Zwraca wartość "object", ponieważ specjalna wartość null jest uważana za puste odniesienie do obiektu. Safari od wersji 5 i Chrome od wersji 7 mają dziwaczność, w której wywołanie typeof w wyrażeniu regularnym zwraca "function", podczas gdy wszystkie inne przeglądarki zwracają"object".

 -1
Author: Jones Agyemang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-06 11:24:28
var x;
if (x === undefined) {
    alert ("only declared, but not defined.")
};
if (typeof y === "undefined") {
    alert ("not even declared.")
};

Możesz użyć tylko drugiego: ponieważ sprawdzi zarówno definicję, jak i deklarację

 -1
Author: keshav,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-15 10:07:37

Nadal uważam, że najlepszym / bezpiecznym sposobem przetestowania tych dwóch warunków jest rzucenie wartości na ciąg znaków:

var EmpName = $("div#esd-names div#name").attr('class');

// Undefined check
if (Object.prototype.toString.call(EmpName) === '[object Undefined]'){
    // Do something with your code
}

// Nullcheck
if (Object.prototype.toString.call(EmpName) === '[object Null]'){
    // Do something with your code
}
 -1
Author: n1kkou,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-03-08 23:23:23

Możesz sprawdzić, czy wartość jest niezdefiniowana lub null, po prostu używając typeof:

if(typeof value == 'undefined'){
 -3
Author: gideon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-26 02:16:47